HandlerExceptionResolvers
Exception handling in Spring involves the use of multiple resolvers. When an error occurs and is addressed by multiple resolvers, it raises questions about the resolution process.
Spring’s default exception resolvers are sequenced as follows:
ExceptionHandlerExceptionResolver, ResponseStatusExceptionResolver, DefaultHandlerExceptionResolver.
Get J’s stories in your inbox
Join Medium for free to get updates from this writer.
These are configured within the WebMvcConfigurationSupport class, and the order of the resolver list can be altered by overriding the configureHandlerExceptionResolvers method.
In the default resolution sequence, methods annotated with @ExceptionHandler take precedence, followed by those annotated with @ResponseStatus, and finally, the DefaultHandlerExceptionResolver. The latter is invoked when the error is not caught by preceding resolvers, and the dispatcher servlet has to handle the exception. BasicErrorController comes in to play, returning appropriate error views corresponding to the HTTP status codes translated by theDefaultHandlerExceptionResolver.
However, instead of going through the dispatcher servlet one more time and routing to the appropriate error pages, a more desirable approach is to handle the exception directly. Therefore, for a streamlined approach to handling exceptions with shared logic, consider using an advice class annotated with @RestControllerAdvice. This class can contain methods with @ExceptionHandler, contributing to code cleanliness and centralizing the handling of exceptions.






