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

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

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:

See also