@ExceptionHandler

@ExceptionHandler() marks a method that turns an exception into the HTTP response. On a controller it handles the errors of that controller's methods; on a @ControllerAdvice bean, those of every controller.

Why

Without a handler, an exception thrown by a controller method is a 500, or the status of an ErrorResponse such as a ResponseStatusException. Services usually throw exceptions of the domain (BookNotFoundException, StateError) that know nothing about HTTP. An exception handler maps them to proper answers in one place: a BookNotFoundException becomes a 404, a conflict a 409 with a useful message. It can also replace the starter's own answers, for example the shape of validation errors.

Example

import 'dart:async';

import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';

class Book {
  const Book({required this.isbn, required this.title});

  final String isbn;
  final String title;
}

class BookNotFoundException implements Exception {
  BookNotFoundException(this.isbn);

  final String isbn;
}

@RestController()
@RequestMapping('/api/books')
class BookController {
  @GetMapping('/{isbn}')
  Book find(@PathVariable() String isbn) => throw BookNotFoundException(isbn);

  @PostMapping('/{isbn}/reserve')
  void reserve(@PathVariable() String isbn) => throw StateError('Already reserved');

  @GetMapping('/{isbn}/price')
  Future<double> price(@PathVariable() String isbn) =>
      Future.delayed(const Duration(seconds: 1), () => throw TimeoutException('slow'));

  // The parameter's type picks the exceptions (subtypes too). The request
  // is optional; the problem names the ISBN.
  @ExceptionHandler()
  @ResponseStatus(HttpStatus.notFound)
  ProblemDetail notFound(BookNotFoundException e, ServerHttpRequest request) =>
      ProblemDetail.forStatusAndDetail(HttpStatus.notFound, 'No book ${e.isbn}')
        ..setProperty('isbn', e.isbn);

  // A ResponseEntity, when the answer needs its own status and headers.
  @ExceptionHandler()
  ResponseEntity<ProblemDetail> conflict(StateError e) =>
      ResponseEntity.status(HttpStatus.conflict)
          .header('Retry-After', ['60'])
          .body(ProblemDetail.forStatusAndDetail(HttpStatus.conflict, e.message));

  // Listed types match by exact runtime type; nothing to say but the status.
  @ExceptionHandler([TimeoutException])
  @ResponseStatus(HttpStatus.gatewayTimeout)
  void timeout() {}
}

Replacing the starter's validation answer, for every controller:

@RestControllerAdvice()
class ValidationErrors {
  // {"isbn": "must not be blank", "title": "must not be blank"}
  @ExceptionHandler()
  @ResponseStatus(HttpStatus.badRequest)
  Map<String, String?> invalid(MethodArgumentNotValidException e) => {
    for (final error in e.bindingResult.fieldErrors())
      error.field: error.defaultMessage,
  };
}

Parameters

Name Type Default Meaning
value (positional) List<Type> const [] Exception types to handle, matched by their exact runtime type: a subtype does not match. Empty: the type of the exception parameter decides.

The method's parameters

A handler method may take, in any order:

Parameter Value
the exception (the first parameter of another type than below) the error; its type decides which errors the method handles
ServerHttpRequest the request
ServerHttpResponse the response
HttpHeaders the request headers

Any other parameter stops the start. So does a handler with neither an exception parameter nor types in value (see Startup checks). Binding annotations (@RequestParam, @PathVariable, ...) are not read on handler parameters; take the request instead.

What it returns

The method returns what a controller method returns, and it is written the same way (see Results). It may be async.

Result Answer
a ProblemDetail application/problem+json with the problem's status, or the @ResponseStatus
a ResponseEntity<T> its status, headers and body
an ErrorResponse (a ResponseStatusException, ...) its status, headers and problem
an object, Map, List, String the body, with the @ResponseStatus status, else 200
void, null the @ResponseStatus status (else 200), no body

Give a handler that returns an object or nothing a @ResponseStatus (or return a ResponseEntity): without it, the error is answered with 200.

Which handler answers

  1. The controller's own handlers come first, for errors thrown while one of its methods handles a request: the method itself, the binding of its parameters (a missing value, a conversion, a @Valid violation), its interceptors, and the writing of its result before the response is committed.
  2. Then the advice beans, in @Order: the first @ControllerAdvice bean that applies to the controller and has a handler for the error answers it, even when a later bean has a more specific one.
  3. Within one controller or bean, the most specific handler wins: a handler that lists the error's exact runtime type in @ExceptionHandler([...]), else the handler whose exception parameter has the most specific type (ArgumentError before Error).

A handler with both value and an exception parameter handles the listed types, and only those instances its parameter type accepts.

Rules:

In Spring (Java)

@ExceptionHandler
@ResponseStatus(HttpStatus.NOT_FOUND)
ProblemDetail notFound(BookNotFoundException e) { ... }

@ExceptionHandler(TimeoutException.class)
@ResponseStatus(HttpStatus.GATEWAY_TIMEOUT)
void timeout() { }

Differences that matter:

See also