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?
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, ie 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.