When an endpoint throws an exception, its HTTP response should still tell the client what went wrong. @RestControllerAdvice provides shared advice for REST controllers, so exception handling can live outside an individual controller action. section 10.3.3
For a payment endpoint, the separation works like this:
- The controller action handles the successful payment flow without a try-catch for the payment exception. section 10.3.3
- A class annotated with @RestControllerAdvice defines shared exception-handling logic. section 10.3.3
- An @ExceptionHandler for NotEnoughMoneyException returns an ErrorDetails body with a 400 Bad Request response. 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);
}
}See the advice class and its exception handler for the payment example. section 10.3.3

