liveBook · Manning

Exception handler

As explained in Spring Start Here, Second Edition

An exception handler is a method that defines the response or other processing performed for a particular exception.

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

How Spring Start Here, Second Edition covers it

How deep it goes
Defines the handler and demonstrates its annotations, response, and optional exception parameter.
Examples
Uses a payment endpoint where NotEnoughMoneyException produces a 400 response containing an error message.
What you can do after
Apply Spring annotations to route a particular exception to separate response-handling logic.
How it connects
Connects exception handling with REST controller advice, exceptions, and HTTP responses.

Also explained in

Compare how 2 books explain exception handler →

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.