2015-10-04 194 views
4
處理

我收到以下錯誤:嵌套異常在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不應該由上面的代碼處理?

回答

1

引用的@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

相關問題