Nested Exception handling in Spring MVC

浪子不回头ぞ 提交于 2019-12-10 15:23:43

问题


I am getting the following error:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException

And to handle this in a controller, I have used the following code:

@ExceptionHandler(NestedServletException.class)
public ModelAndView handleServletErrors(){
    System.out.println("Servlet Exception is thrown");
    ModelAndView mv = new ModelAndView("error"); 
    mv.addObject("error", "Error encountered while processing reqeust.");
    return mv;
}

But this does not handle the exception thrown above. Whereas if I use NullPointerException class instead of NestedServletException, it works. Since Spring is throwing exception in response to NullPointerException shouldn't it be handled by the code above?


回答1:


Quoting the documentation of @ExceptionHandler:

Annotation for handling exceptions in specific handler classes and/or handler methods.

This annotation will allow a method to handle exceptions that are thrown by handler methods, i.e. methods that are annotated with @RequestMapping. Quoting the Spring reference:

You can do that with @ExceptionHandler methods. When declared within a controller such methods apply to exceptions raised by @RequestMapping methods of that contoroller (or any of its sub-classes). You can also declare an @ExceptionHandler method within an @ControllerAdvice class in which case it handles exceptions from @RequestMapping methods from many controllers.

Since the exception thrown by your handler is NullPointerException, the exception handler method will handle that specific exception. It will not handle the generic NestedServletException that Spring uses to encapsulate servlet exceptions.



来源:https://stackoverflow.com/questions/32933854/nested-exception-handling-in-spring-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!