liveBook · Manning

@ExceptionHandler

As explained in Spring Start Here, Second Edition

The @ExceptionHandler annotation identifies a method that handles specified exceptions thrown during controller request processing.

@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

How Spring Start Here, Second Edition covers it

How deep it goes
Explains exception-type selection, response creation, and passing exception details, without detailing framework internals.
Examples
Uses NotEnoughMoneyException in a payment endpoint to return a bad-request response with an error message.
What you can do after
Apply the annotation in REST controller advice to handle a specified exception and return an HTTP response.
How it connects
Connects REST controller advice with REST endpoints and HTTP responses.

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.