Leobejj
Leobejj

Reputation: 51

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?

Upvotes: 1

Views: 849

Answers (1)

Iv&#225;n Larios
Iv&#225;n Larios

Reputation: 161

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
  }

}

Upvotes: 2

Related Questions