为什么 Spring 异常处理程序没有按预期工作

君主不*_*不是你 0 spring-mvc

当我@ExceptionHandler在控制器中使用时,它没有按预期工作。

这是我的代码:

@Controller
public class PageController {

    @RequestMapping("/page")
    public ModelAndView index(ModelAndView modelAndView){
        String mess = null;
        mess.split(",");
        modelAndView.setViewName("index");
        return modelAndView;
    }

    @ExceptionHandler({Exception.class})
    @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Bad Request")
    public ModelAndView handleException(Exception ex, HttpServletRequest request,     HttpServletResponse response){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message", ex.getMessage());
        modelAndView.addObject("url", request.getRequestURL());
        modelAndView.addObject("code", response.getStatus());
        modelAndView.setViewName("exception");
        return modelAndView;
    }
}
Run Code Online (Sandbox Code Playgroud)

应用程序以调试模式启动后,我访问http://localhost:8080/page,并且handleException正在运行,但视图低于预期excepction视图。为什么?

在此输入图像描述

rie*_*pil 5

问题出在@ResponseStatus注释上。看看下面的文章: http: //blog.sizovs.net/spring-rest-exception-handler/。在这篇文章的中间,作者说:

警告:当在异常类上使用此注解时,或者设置此注解的reason属性时,HttpServletResponse.sendError将使用该方法。使用 时HttpServletResponse.sendError,响应被认为是完整的,不应再写入任何内容。此外,Servlet 容器通常会编写 HTML 错误页面,因此不适合 REST API。对于这种情况,最好使用 aorg.springframework.http.ResponseEntity作为返回类型并完全避免使用@ResponseStatus

根据 Spring 文章:https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc,Spring MVC 按以下顺序链接以下三个解析器:

  • ExceptionHandlerExceptionResolver 将未捕获的异常与处理程序(控制器)和任何控制器建议上合适的 @ExceptionHandler 方法进行匹配。
  • ResponseStatusExceptionResolver 查找由 @ResponseStatus 注释的未捕获异常(如第 1 节中所述)
  • DefaultHandlerExceptionResolver 转换标准 Spring 异常并将它们转换为 HTTP 状态代码(我上面没有提到这一点,因为它是 Spring MVC 的内部)。

所以ResponseStatusExceptionResolver在 后触发ExceptionHanlderExceptionResolver并使用默认值并会显示 Spring 的错误页面。

如需快速修复,请尝试删除@ResponseStatus,您应该会在浏览器中看到自定义错误页面。