An exception handler is a method that defines what happens when a particular exception is thrown. In a Spring REST API, a controller advice can keep this logic out of the endpoint action, leaving the action to handle the happy flow. 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);
}
}For a payment endpoint, this advice handles NotEnoughMoneyException and returns a 400 Bad Request response with an error message. Add an exception parameter to the handler when its logic needs details from the thrown exception. section 10.3.3

