SpringBoot中CustomErrorController被忽略,直接跳转error.html问题求助
我明白你的困扰——明明写了自定义的CustomErrorController映射到/error,结果Spring直接跳去error.html,完全没经过你的控制器,导致没法添加自定义的errorMsg。别着急,咱们一步步来解决这个问题:
为什么会出现这个情况?
Spring Boot的错误处理机制里,当静态资源或模板目录下存在error.html时,默认的ErrorViewResolver会优先直接解析这个视图。但如果你的CustomErrorController没有被Spring正确识别和注册,请求就会走默认的错误视图流程,跳过你的控制器。
解决方案步骤
1. 确保你的CustomErrorController被Spring管理
首先,给你的控制器加上@Controller注解,让Spring能扫描到它并注册为Bean。同时要保证这个类所在的包被@ComponentScan覆盖(一般Spring Boot启动类的包会自动扫描子包,所以把控制器放在启动类的子包下就行)。
2. 修正CustomErrorController的代码逻辑
调整控制器方法,确保它能处理/error请求,添加自定义错误信息后,再返回error.html视图。示例代码如下:
@Controller public class CustomErrorController implements ErrorController { private static final String ERROR_PATH = "/error"; @RequestMapping(value = ERROR_PATH) public ModelAndView renderErrorPage(HttpServletRequest request) { ModelAndView modelAndView = new ModelAndView("error"); // 指定渲染error.html视图 // 自定义错误信息逻辑 String customErrorMsg = buildCustomErrorMsg(request); modelAndView.addObject("errorMsg", customErrorMsg); // 将自定义信息传入视图 return modelAndView; } private String buildCustomErrorMsg(HttpServletRequest request) { // 从request中获取错误相关信息,比如状态码、异常 Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception"); if (statusCode != null) { return String.format("请求失败,状态码:%d,原因:%s", statusCode, exception != null ? exception.getMessage() : "未知错误"); } return "系统未知错误"; } // Spring Boot 2.3+ 版本此方法已过时,但为了兼容性可以保留 @Override public String getErrorPath() { return ERROR_PATH; } }
3. 调整error.html的位置和内容
把error.html放在模板目录(比如src/main/resources/templates,如果你用Thymeleaf等模板引擎),这样才能渲染控制器传入的errorMsg变量。比如在error.html中添加:
<p>自定义错误提示:<span th:text="${errorMsg}"></span></p>
如果你的项目没用到模板引擎,也可以把error.html放在静态资源目录,但这时候无法直接渲染模型变量,建议引入Thymeleaf来方便处理视图数据。
4. 确认默认BasicErrorController已被替换
Spring Boot默认的BasicErrorController会在没有自定义ErrorController时生效。只要你的CustomErrorController被正确注册,Spring就不会再创建默认的BasicErrorController。你可以通过启动日志查看是否有类似CustomErrorController的Bean被加载,来验证这一点。
这样调整后,所有错误请求都会先经过你的CustomErrorController,添加好自定义错误信息后,再渲染error.html页面,完美解决你的需求~
内容的提问来源于stack exchange,提问作者Audiosleef

