You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot设置默认/error路径时为何忽略自定义CustomErrorController?

解决Spring Boot默认/error路径覆盖问题

问题原因

Spring Boot自动配置的BasicErrorController会默认绑定到/error路径,当你自定义的ErrorController也映射到该路径时,默认控制器的优先级更高,导致你的实现被忽略。

解决方案

方案1:让自定义控制器优先加载

在你的CustomErrorController上添加@Primary注解,确保Spring容器优先选择你的实现而非默认的BasicErrorController,同时适配不同版本的Spring Boot要求:

@Controller
@Primary
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    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;
    }

    // Spring Boot 2.3以下版本需实现此方法,2.3及以上可省略,推荐用server.error.path配置
    @Override
    public String getErrorPath() {
        return "/error";
    }
}

配置保持:

server.error.path=/error

方案2:排除默认错误自动配置

在Spring Boot启动类上添加exclude参数,直接禁用默认的错误处理自动配置:

@SpringBootApplication(exclude = ErrorMvcAutoConfiguration.class)
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

注意:此方式会完全移除默认错误处理逻辑,需确保你的自定义控制器能覆盖所有错误场景。

方案3:自定义ErrorViewResolver(无需替换ErrorController)

如果仅需自定义错误视图,无需完全接管错误处理,可实现ErrorViewResolver接口,Spring Boot会自动使用它匹配对应状态码的视图:

@Component
public class CustomErrorViewResolver implements ErrorViewResolver {

    @Override
    public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
        String viewName = switch (status.value()) {
            case 403 -> "errors/403";
            case 404 -> "errors/404";
            case 500 -> "errors/500";
            default -> "error";
        };
        return new ModelAndView(viewName, model);
    }
}

这种方式无需修改server.error.path或自定义ErrorController,更轻量化。

内容的提问来源于stack exchange,提问作者Slevin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 18:55:13