【问题标题】:Why does Spring Boot ignore my CustomErrorController?为什么 Spring Boot 会忽略我的 CustomErrorController?
【发布时间】:2022-12-04 20:12:31
【问题描述】:

我有一个像这样的自定义 ErrorController:

@Controller
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error42")
    public String handleError(HttpServletRequest request) {
      
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        System.err.println(status);

        if (Objects.isNull(status)) return "error";

        int statusCode = Integer.parseInt(status.toString());
        String view = switch (statusCode) {
            case 403 -> "errors/403";
            case 404 -> "errors/404";
            case 500 -> "errors/500";
            default -> "error";
        };

        return view;
    }
}

然后我设置了 server.error.path 属性,如下所示:

server.error.path=/error42

到目前为止,一切都很好。一切正常。所有错误都通过我的 CustomErrorController。

但是当我将错误路径设置为server.error.path=/error时——当然我将请求映射注释更改为@RequestMapping("/error")——这将不再起作用。

Spring Boot 现在完全忽略了我的 CustomErrorController。我知道,我已经将路径设置为 Spring Boot 通常定义为标准的路径,但是没有办法覆盖它吗?

非常感谢您提供消除这种奇怪行为的任何信息。

【问题讨论】:

    标签: spring spring-boot error-handling


    【解决方案1】:

    我发现了错误,这完全是我自己的错。由于特别是在 Spring Boot 职业生涯的开始,设置选项很快变得势不可挡,并且可能会忽略所做的一项或另一项调整,所以我仍然想留下这个问题并自己回答。

    罪魁祸首是我几周前做的一个自我配置的视图,完全忘记了:

    @Configuration
    @EnableWebMvc
    public class WebMvcConfig implements WebMvcConfigurer {
    
        /* FYI: will map URIs to views without the need of a Controller */
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/login")
                    .setViewName("/login");
    
            registry.addViewController("/error")  // <--- Take this out !!!
                    .setViewName("/error");
    
            registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        }
    }
    

    愿这能帮助其他人面对同样的谜团,为什么再一次没有任何事情按预期运行......

    【讨论】:

      猜你喜欢
      • 2018-09-08
      • 2018-06-14
      • 2017-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      相关资源
      最近更新 更多