liveBook · Manning

@RestControllerAdvice

As explained in Spring Start Here, Second Edition

@RestControllerAdvice is a Spring annotation for applying shared advice, including exception handling, to REST controllers.

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

How Spring Start Here, Second Edition covers it

How deep it goes
Works through a payment exception handler and HTTP error response, contrasting advice with controller-level try-catch handling.
Examples
Uses a payment endpoint that throws NotEnoughMoneyException and returns an error message with 400 Bad Request.
What you can do after
Apply it with Spring annotations to move exception-response logic out of a REST controller action.
How it connects
Connects REST controllers with exception handling, @ExceptionHandler, ResponseEntity, and HTTP response statuses.

Also explained in

Compare how 2 books explain @RestControllerAdvice →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Start Here, Second Edition. The section links point to the parts of the book it draws on.