Video in progress
If several @ExceptionHandler methods match one exception, which one does Spring pick?
Within a single advice, the handler closest to the exception in the hierarchy is chosen. If there are several advices, Spring looks at them in @Order, and the first advice that has a matching handler wins, even if another one has a more specific handler.
📖 Answer
Within a single class:
@RestControllerAdvice
class ApiErrors {
@ExceptionHandler(RuntimeException.class)
ProblemDetail any(RuntimeException e) { ... } // general
@ExceptionHandler(EntityNotFoundException.class)
ProblemDetail notFound(EntityNotFoundException e) { ... } // specific
}
If EntityNotFoundException is thrown, the second one runs, because it's closer to the exception in the hierarchy.
A handler inside a controller is always checked before the global advice.
With several advices, here is the trap:
@RestControllerAdvice // no @Order
class GlobalErrors {
@ExceptionHandler(Exception.class) ...
}
@RestControllerAdvice
class PaymentErrors {
@ExceptionHandler(PaymentDeclinedException.class) ...
}
Spring goes through the advices in order and takes the first advice that can handle Exception. If GlobalErrors comes first, the general response is returned even for PaymentDeclinedException. If you don't set an order, the outcome is nearly random.
The fix: @Order(Ordered.HIGHEST_PRECEDENCE) on the specific advices and @Order(Ordered.LOWEST_PRECEDENCE) on the general catch-all. Or limit the advice with basePackages/assignableTypes.
One more subtle point: a handler that catches Exception.class can also swallow Spring Security's AccessDeniedException and return 500 instead of 403.
Sign up to mark studied questions and save your progress.