【问题标题】:Java Spring Boot Web App: Handling 404 ExceptionJava Spring Boot Web App:处理 404 异常
【发布时间】:2020-10-10 08:21:39
【问题描述】:

我正在学习 Java Spring Boot 教程,并且正在尝试处理 404 异常。我有教程中的确切代码,但由于某种原因它不起作用,尽管 403 错误正在工作。在本教程中,讲师处理所有未决异常的方式如下,特别是 defaultErrorHandler()。但是,这不起作用:

@ControllerAdvice
public class GlobalExceptionHandler {

    @Value("${message.error.exception}")
    private String exceptionMessage;

    @Value("${message.error.duplicate.user}")
    private String duplicateUserMessage;

    @ExceptionHandler(value=Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.getModel().put("message", exceptionMessage);
        modelAndView.getModel().put("url", req.getRequestURL());
        modelAndView.getModel().put("exception", e);
        modelAndView.setViewName("app.exception");
        return modelAndView;
    }

    @ExceptionHandler(value=DataIntegrityViolationException.class)
    public ModelAndView duplicateUserHandler(HttpServletRequest req, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.getModel().put("message", duplicateUserMessage);
        modelAndView.getModel().put("url", req.getRequestURL());
        modelAndView.getModel().put("exception", e);
        modelAndView.setViewName("app.exception");
        return modelAndView;
    }
}

然后我尝试添加类似于讲师处理 403 错误的内容,如下所示,但这也不起作用:

    @RequestMapping("/403")
    ModelAndView accessDenied(ModelAndView modelAndView) {
        System.out.println("We're here");
        modelAndView.getModel().put("message", accessDeniedMessage);
        modelAndView.setViewName("app.message");
        return modelAndView;

    }

    @RequestMapping("/404")
    ModelAndView pageNotFound(ModelAndView modelAndView) {

        modelAndView.getModel().put("message", exceptionMessage);
        modelAndView.setViewName("app.message");
        return modelAndView;

    }

我尝试通过将 System.out.println("test") 放入每个可疑方法中进行调试,但都没有达到。任何帮助,将不胜感激。谢谢!

【问题讨论】:

  • 当您说However, this is not working 时,您遇到的错误是什么?有日志吗?
  • 尝试强制throw new DataIntegrityViolationException( "Exception forced to happen" ) 看看是否有效。查看记录的任何异常。对我来说ExceptionHandler 代码看起来不错
  • 抱歉回复晚了,但是是的,当我尝试转到未知网址而不是被定向到为用户处理 404 错误的自定义页面时,我得到以下信息:[nio-8080-exec-1] osweb.servlet.DispatcherServlet : 退出“ERROR”调度,状态 404。我设置了无论用户在 localhost:8080/ 之后输入什么,他们最初都会被定向到 localhost:8080/登录页面。但是,一旦登录,如果他们在 localhost:8080/ 之后键入任何不是应用程序 url 的内容,那么我会错误地收到白标错误。

标签: java spring-boot web error-handling http-status-code-404


【解决方案1】:

如果您想处理 404 异常以显示您的自定义页面而不是可白标错误。您可以通过在资源目录中创建名为 error 的文件夹来实现。在错误文件夹中创建 404.html 文件并添加 html 代码、样式等。 现在 Spring Boot 会选择您的 404.html 文件并在发生 404 错误时向用户显示。这样您也可以处理任何错误,只需输入错误代码 501.html、407.html 等的文件名

【讨论】:

    猜你喜欢
    • 2016-09-29
    • 2022-11-22
    • 1970-01-01
    • 2023-03-28
    • 2018-03-16
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    相关资源
    最近更新 更多