'Can I directly invoke the Spring exception resolvers?

My servlet request thread invokes a worker thread that can throw exceptions of many possible types. The worker thread catches any exception and passes it back to the request thread. I'd like to get that exception to the correct handler method in my Spring controller.

You cannot rethrow an exception from one thread in another thread, so the request thread wraps the original exception and throws that. That wrapper exception is currently being handled by a catch-all controller method annotated with @ExceptionHandler(Throwable.class). Because this handler exists, Spring does not look at the nested exception, so the nested exception is ignored.

I can add a handler for the wrapper exception type. In that, I'd like to unwrap the nested exception and ask Spring to route it to the correct handler. I've learned that Spring handles exceptions via a chain of resolvers that implement HandlerExceptionResolver. Is there a way I can invoke that chain directly from my handler?



Solution 1:[1]

Inject List<HandlerExceptionResolver> handlerExceptionResolvers into your controller, then go through the list and try to handle the exception. If it returns a non-null ModelAndView, this means the request has been handled:

    Exception e = ...;
    if(e != null) 
        for (HandlerExceptionResolver resolver : handlerExceptionResolvers) 
            if (resolver.resolveException(req, resp, null, e) != null)
                return null;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1