ExceptionHandler doesn’t work with Throwable

Contrary to what the ExceptionHandler#value() attribute indicates

Class<? extends Throwable>[] value() default {};

and @ExceptionHandler is only meant to handle Exception and its sub types.

Spring uses ExceptionHandlerExceptionResolver to resolve your annotated handlers, using the following method

doResolveHandlerMethodException(HttpServletRequest request,
        HttpServletResponse response, HandlerMethod handlerMethod, Exception exception) 

which as you can see only accepts an Exception.

You cannot handle Throwable or Error types with @ExceptionHandler with this configuration.

I would tell you to provide your own HandlerExceptionResolver implementation which does handle Throwable instances, but you’d need to provide your own DispatcherServlet (and most of the MVC stack) yourself since DispatcherServlet does not catch Throwable instances at any place where you could make any significant difference.


Update:

Since 4.3, Spring MVC wraps a thrown Throwable value in a NestedServletException instance and exposes that to the ExceptionHandlerExceptionResolver.

Leave a Comment