SpringBoot自定义ErrorAttributes对text/html响应不生效问题求助
问题原因
SpringBoot的错误处理逻辑针对不同的Accept请求头有两套分支:
- 当Accept为
application/json时,直接通过ErrorAttributes组装JSON响应体,所以你自定义的MyCustomErrorAttributes修改会直接生效。 - 当Accept为
text/html时,会通过ErrorViewResolver(默认是DefaultErrorViewResolver)匹配错误视图(比如默认的白标错误页面)。默认的白标错误页面是硬编码渲染status、message等字段,部分属性甚至直接从请求或错误对象中读取,而非完全依赖你修改后的ErrorAttributes数据,导致你的修改不生效。
解决方法
方法1:自定义错误页面(推荐)
创建自定义的错误页面(比如使用Thymeleaf模板),只渲染你需要的属性,避免展示status、message:
- 在
src/main/resources/templates/下创建error.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Error</title> </head> <body> <h1>An error occurred</h1> <p>Locale: [[${locale}]]</p> </body> </html>
- 确保你的自定义
MyCustomErrorAttributes已注册为Spring Bean(添加@Component注解),这样模型中会包含你添加的locale属性,自定义页面会渲染该属性,且不会展示被移除的status、message。
方法2:自定义ErrorViewResolver,强制使用修改后的ErrorAttributes
通过自定义ErrorViewResolver,让HTML错误视图的模型完全使用你修改后的ErrorAttributes数据:
@Component public class CustomErrorViewResolver extends DefaultErrorViewResolver { private final ErrorAttributes errorAttributes; public CustomErrorViewResolver(ApplicationContext applicationContext, ResourceProperties resourceProperties, ErrorAttributes errorAttributes) { super(applicationContext, resourceProperties); this.errorAttributes = errorAttributes; } @Override public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) { // 清空默认模型,替换为自定义ErrorAttributes的属性 model.clear(); ServletWebRequest webRequest = new ServletWebRequest(request); model.putAll(errorAttributes.getErrorAttributes(webRequest, ErrorAttributeOptions.defaults())); // 调用父类方法返回对应视图 return super.resolveErrorView(request, status, model); } }
这样默认的白标错误页面会使用你修改后的模型数据,不会展示status、message,同时会显示locale。
方法3:检查自定义ErrorAttributes的逻辑
确保你的MyCustomErrorAttributes实现正确:
@Component public class MyCustomErrorAttributes extends DefaultErrorAttributes { @Override public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) { Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, options); // 移除指定属性 errorAttributes.remove("message"); errorAttributes.remove("status"); // 添加locale属性 errorAttributes.put("locale", webRequest.getLocale().toString()); return errorAttributes; } }
注意:不要限制ErrorAttributeOptions的属性范围,确保你能获取到所有默认属性后再进行移除操作。
内容的提问来源于stack exchange,提问作者user17968709
相关产品推荐
相关产品推荐

