HandlerExceptionResolver
A HandlerExceptionResolver bean turns an error into an answer for the errors that no @ExceptionHandler method handles. It returns an ErrorResponse (a status, headers and a ProblemDetail), or null to pass the error on.
Why
It is how a library maps its own exceptions to HTTP without the application writing an advice for them. The data starter, for one, answers a version conflict with a 409 instead of a 500. The application's own @ExceptionHandler methods always come first, so it can still answer any of these errors its own way.
An application can use one too, for a rule that is easier to write as code than as handler methods: a whole family of exceptions mapped by a table, or a mapping that depends on the request.
Example
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';
class RoomTakenException implements Exception {}
class RoomClosedException implements Exception {
RoomClosedException(this.until);
final DateTime until;
}
// A booking that fails because the room is taken answers 409.
@Component()
@Order(10)
class RoomTakenResolver implements HandlerExceptionResolver {
@override
ErrorResponse? resolveException(
ServerHttpRequest request,
Object error, {
HandlerMethod? handler,
}) => error is RoomTakenException
? ResponseStatusException(HttpStatus.conflict, 'The room is taken')
: null;
}
// A closed room: 503 with Retry-After, and the date in the problem.
@Component()
@Order(20)
class RoomClosedResolver implements HandlerExceptionResolver {
@override
Future<ErrorResponse?> resolveException(
ServerHttpRequest request,
Object error, {
HandlerMethod? handler,
}) async {
if (error is! RoomClosedException) {
return null;
}
return ErrorResponseException(
HttpStatus.serviceUnavailable,
headers: HttpHeaders()
..set(HttpHeaders.retryAfterHeader, HttpHeaders.formatDate(error.until)),
body: ProblemDetail.forStatusAndDetail(
HttpStatus.serviceUnavailable,
'The room is closed',
)..setProperty('until', error.until.toIso8601String()),
);
}
}
The interface
abstract interface class HandlerExceptionResolver {
FutureOr<ErrorResponse?> resolveException(
ServerHttpRequest request,
Object error, {
HandlerMethod? handler,
});
}
| Parameter | Type | Meaning |
|---|---|---|
request |
ServerHttpRequest |
The request that failed. |
error |
Object |
The error. |
handler |
HandlerMethod? |
The controller method that was handling the request (its description, beanName, annotation<A>()), or null when the error came before a method was chosen. |
| result | FutureOr<ErrorResponse?> |
The answer, or null for an error that is not this resolver's. May be asynchronous. |
Rules
- Declare it as a bean (
@Component(), or a@Beanmethod). Rank several with@Order; lower runs first. - When they are asked. After the
@ExceptionHandlermethods of the controller and of the advice beans, before the default 500. The resolvers are asked in@Order, and the first that returns an answer wins;nullpasses the error to the next one. - What they do not see. An error that is already an
ErrorResponse(aResponseStatusException, the router's 404, 405, 406 and 415, a validation error): it carries its answer, as in Spring, whereResponseStatusExceptionResolveranswers it first. An error thrown by aWebFilterskips them too. They see the errors of the controllers, their interceptors, the binding of their arguments, and of other handler mappings. - The answer is written like a thrown
ErrorResponse: its status, its headers (aVaryadds its names to those already there, such as the CORS ones) and its problem, asapplication/problem+json. The problem'sinstanceis the request path when not set. - Keep the detail generic. It goes to the client, and an exception's message may hold SQL, table names or values.
- Logging. Each resolved error is logged at debug level under
spring.web.mvc, with the error'stoString(), the status and the resolver:Resolved [Instance of 'RoomTakenException'] as 409 by RoomTakenResolver. No warning is logged for it, even for a 5xx answer: give your exception atoString()that helps when you read the debug log. - A resolver that throws is logged as a warning and skipped; the next one is asked.
- One chance per error. A resolver is asked at most once for the same error of a request.
Resolvers that libraries register
The data starter: dataAccessExceptionResolver
An application that depends on both spring_boot_starter_web and spring_boot_starter_data gets a resolver without writing one. Neither starter may depend on the other, so the generator adds the bean dataAccessExceptionResolver to the application's module (the same way it adds the database driver).
| Exception | Status | Detail |
|---|---|---|
OptimisticLockingFailureException (a @Version conflict) |
409 | The resource was changed by someone else |
DuplicateKeyException |
409 | The resource already exists |
EmptyResultDataAccessException |
404 | Not found |
PropertyReferenceException |
400 | Invalid sort property |
InvalidPagingRequestException |
400 | Invalid page or sort request |
InvalidDataArgumentException |
400 | Invalid request value |
- Subtypes are mapped too.
- The detail is fixed, never the exception's message, which may hold SQL, table names or values. The exception is kept as the
cause, which is not sent. - Every other data error stays a 500 without details, as any other exception.
- To replace it, declare a bean named
dataAccessExceptionResolver; to answer one of these errors differently, write an@ExceptionHandlerfor it, which comes first.
In Spring (Java)
@Component
class RoomTakenResolver implements HandlerExceptionResolver {
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
if (!(ex instanceof RoomTakenException)) return null;
response.setStatus(HttpServletResponse.SC_CONFLICT);
return new ModelAndView();
}
}
Differences that matter:
- The resolver returns an
ErrorResponse(ornull) instead of writing into the response and returning aModelAndView. - Spring's built-in resolvers are the
@ExceptionHandlermethods (ExceptionHandlerExceptionResolver),ResponseStatusExceptionandErrorResponsehandling andDefaultHandlerExceptionResolver. Here those are built in, and the resolver beans are always asked after them. @ResponseStatuson exception classes (ResponseStatusExceptionResolver) is not read.