我收到以下错误:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
为了在控制器中处理这个问题,我使用了以下代码:
@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;
}
但是这并没有处理上面抛出的异常.如果我使用NullPointerException类而不是NestedServletException,它可以工作.由于Spring在响应NullPointerException时抛出异常,不应该由上面的代码处理吗?
最佳答案 引用
@ExceptionHandler
的文档:
Annotation for handling exceptions in specific handler classes and/or handler methods.
此注释将允许方法处理由处理程序方法引发的异常,即使用@RequestMapping注释的方法.引用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.
由于处理程序抛出的异常是NullPointerException,因此异常处理程序方法将处理该特定异常.它不会处理Spring用来封装servlet异常的泛型NestedServletException.