简体   繁体   中英

How to use @ControllerAdvice for catching exceptions from Service classes?

I have some Service classes which contain multiple methods that throws error, an example of methods that throws an error:

public Optional<Item> getItemById(Long itemId) throws Exception {
        return Optional.of(itemRepository.findById(itemId).
                orElseThrow(() -> new Exception("Item with that id doesn't exist")));
    }

Should I catch errors in the @ControllerAdvice annoted class? How should I do it?

The controller marked with @ControllerAdvice will intercept any exception thrown in the stack called when a request arrives. If the question is if you should catch errors with ControllerAdvice, is up to you, but it allows you to customize the behaviour once a exception is thrown. To do it you should create a class like this:

@ControllerAdvice
public class GlobalExceptionHandler {

  @ExceptionHandler({ Exception.class, MyCustomException.class }) //Which exceptions should this method intercept
  public final ResponseEntity<ApiError> handleException(Exception ex){
    return new ResponseEntity<>(body, HttpStatus.NOT_FOUND); //Or any HTTP error you want to return
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM