gpt4 book ai didi

java - Spring MVC 中的嵌套异常处理

转载 作者:搜寻专家 更新时间:2023-11-01 03:20:07 24 4
gpt4 key购买 nike

我收到以下错误:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException

为了在 Controller 中处理这个问题,我使用了以下代码:

@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

关于java - Spring MVC 中的嵌套异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32933854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com