How can I configure Spring 4.0.5 to use @ExceptionHandler instead of ExceptionResolver?
I've added an @ExceptionHandler method to a specific controller.
@ExceptionHandler(NullPointerException.class)
@ResponseStatus(HttpStatus.Not_FOUND)
public @ResponseBody doSomeThing(NullPointerException e) {...}
Problem: I also have a custom
org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver
defined as @Component in my Legacy app.
Now @ExceptionHandler in my specific controller is never called. I need to support both exception handling strategies.
How can I configure spring 4.0.5 to call my @ExceptionHandler in my controller?
source to share
By default, it will DispatcherServlet
download and register all implementations HandlerExceptionResolver
in ApplicationContext
to help you handle Exceptions from your Controllers
. You will notice that the class AbstractHandlerExceptionResolver
implements Ordered
. Most implementations HandlerExceptionResolver
extend this class, and DispatcherServlet
use it to organize the list of implementations HandlerExceptionResolver
when it comes to handling Exceptions thrown by yours Controllers
.
As you might suspect, annotation processing @ExceptionHandler
on yours is Controllers
also done by the implementation HandlerExceptionResolver
. To be precise:org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver
I would guess that what happens in your case is that the type HandlerExceptionResolver
from DispatcherServlet
is calling your implementation before AnnotationMethodHandlerExceptionResolver
, which means that your annotations are @ExceptionHandler
effectively ignored.
To counteract this, we need to do two things:
- Register directly
AnnotationMethodHandlerExceptionResolver
as a bean in yourApplicationContext
- Set
Order
this bean to a value greater than your custom implementationHandlerExceptionResolver
This would mean that when it comes to handling Exceptions
for yours Controllers
, Spring will first see if it can AnnotationMethodHandlerExceptionResolver
handle the exception, and if not, fall back to its custom implementation HandlerExceptionResolver
.
As an example of setting order to HandlerExceptionResolver
(assuming you are using XML config somewhere):
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver" p:order="1" />
You can also view a list of implementations HandlerExceptionResolver
, registered with DispatcherServlet
the default, and choose the procedure that is most appropriate for your application.
source to share