Spring 3 problems with controller exception handler

I was hoping to implement a single "ExceptionController" to handle exceptions that are thrown when other methods of my controllers execute. I did not specify HandlerExceptionResolver in my application context, so AnnotationMethodHandlerExceptionResolver should be triggered according to the API documentation . I checked it as such in the source. So why doesn't the following work?

@Controller public class ExceptionController { @ExceptionHandler(NullPointerException.class) public ModelAndView handleNullPointerException(NullPointerException ex) { // Do some stuff log.error(logging stuff) return myModelAndView; } } @Controller public class AnotherController { @RequestMapping(value="/nullpointerpath") public String throwNullPointer() { throw new NullPointerException(); } } 

In the debug logs, I see that three exception handlers are requested by default to handle the exception, but nothing has been done, and I see that "DispatcherServlet - request failed." After that, the user displays the stack and internal error 500.

+7
java spring-mvc exception-handling
source share
3 answers

Ensure that the Exception handler returns a view that exists / maps to the handler.

+6
source share

You must write your exception handler in the same class with which you want to handle, for example, as follows.

 @Controller public class AnotherController { @ExceptionHandler(NullPointerException.class) public ModelAndView handleNullPointerException(NullPointerException ex) { // Do some stuff. log.error(logging stuff) return myModelAndView; } @RequestMapping(value="/nullpointerpath") public String throwNullPointer() { throw new NullPointerException(); } } 
+4
source share

I do not think this is a good design. Controllers in Spring process HTTP requests and map to URLs. I don't think the β€œexception” fits into any bit. This seems like misuse of Spring for me.

An exception is not an HTTP request. You do not map the exception to a URL. Therefore, I would conclude that controllers are not designed to handle exception handlers.

Controllers are part of the Spring API, but your design does not use them for their intended purpose, so it does not work. Change your mind.

+1
source share

All Articles