@ExceptionHandler marks a method to handle specified exceptions thrown while a controller processes a request. It keeps exception-response logic out of the controller’s happy path. section 10.3.3
In a REST controller advice, the annotation names the exception type that triggers the handler. The handler can build an HTTP response; it can also accept the exception as a parameter to use its details. section 10.3.3
Listing 10.15 Separating the exception logic with a REST controller advice
@RestControllerAdvice #A
public class ExceptionControllerAdvice {
@ExceptionHandler(NotEnoughMoneyException.class) #B
public ResponseEntity<ErrorDetails> exceptionNotEnoughMoneyHandler() {
ErrorDetails errorDetails = new ErrorDetails();
errorDetails.setMessage("Not enough money to make the payment.");
return ResponseEntity
.badRequest()
.body(errorDetails);
}
}The payment example handles NotEnoughMoneyException in a separate advice and returns a 400 response with error details. section 10.3.3
