我收到以下错误:
org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是 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 https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ExceptionHandler.html:
用于处理特定处理程序类和/或处理程序方法中的异常的注释。
此注释将允许方法处理由处理程序方法抛出的异常,即用注释的方法@RequestMapping
。引用弹簧参考 http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-exceptionhandler:
你可以这样做@ExceptionHandler
方法。当在控制器中声明时,此类方法适用于由@RequestMapping
该控制器(或其任何子类)的方法。您还可以声明一个@ExceptionHandler
内的方法@ControllerAdvice
类在这种情况下处理异常@RequestMapping
来自许多控制器的方法。
由于您的处理程序抛出的异常是NullPointerException
,异常处理程序方法将处理该特定异常。它不会处理通用的NestedServletException
Spring用来封装servlet异常。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)