嵌套异常在Spring MVC

问题描述:

处理

我收到以下错误:嵌套异常在Spring MVC

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