@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
- 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
@Validviolation), its interceptors, and the writing of its result before the response is committed. - 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. - 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 (ArgumentErrorbeforeError).
A handler with both value and an exception parameter handles the listed types, and only those instances its parameter type accepts.
Rules:
- Errors before a method was chosen (the router's 404, 405, 406, 415 and the 400 of unmet header conditions) and the errors of other handler mappings (WebSocket handshakes) reach the advice handlers only, and only advice that is not narrowed to some controllers.
- Errors thrown by a filter reach no handler.
- The 503 of
server.request-timeoutreaches no handler: the handler is still running when it is answered. - A handler that throws is logged as a warning (
The @ExceptionHandler ... failed handling ...), and the original error goes on to the next step (see Errors). - A committed response gets no handler: once the status and headers are out, the connection is dropped.
HandlerInterceptor.afterCompletionstill receives the exception, even when a handler answered it.- The built-in exceptions can be handled like any other:
NoHandlerFoundException(in an advice),MissingRequestValueException,MethodArgumentTypeMismatchException,HttpMessageNotReadableException(itsmessagesays why),MethodArgumentNotValidException(itsbindingResulthas the violations), and the others of Errors.
In Spring (Java)
@ExceptionHandler
@ResponseStatus(HttpStatus.NOT_FOUND)
ProblemDetail notFound(BookNotFoundException e) { ... }
@ExceptionHandler(TimeoutException.class)
@ResponseStatus(HttpStatus.GATEWAY_TIMEOUT)
void timeout() { }
Differences that matter:
@ExceptionHandler([types])matches exact runtime types, because Dart cannot test whether oneTypeis a subtype of another. Subtypes match through the type of the exception parameter (@ExceptionHandler() void on(StateError e)).- The parameters are limited to the exception, the request, the response and the headers. Spring also takes
WebRequest,Locale,Modeland others. - A handler without a
@ResponseStatusthat returns an object answers 200, as in Spring. - More mistakes stop the start: an unknown parameter, a handler without an exception type.