Spring Boot从2.3.12升级到2.7.12后getErrorAttributes报错求助
问题原因与解决方案
问题根源
Spring Boot 2.3.x 升级到 2.7.x 时,AbstractErrorController 中的 getErrorAttributes 方法发生了API 破坏性变更:
- 2.3.x 版本的方法签名是:
protected Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) - 2.7.x 版本改为:
protected Map<String, Object> getErrorAttributes(HttpServletRequest request, ErrorAttributeOptions options)
你代码中传入的 isIncludeStackTrace(request, MediaType.APPLICATION.JSON) 返回 boolean 类型,与新版本要求的 ErrorAttributeOptions 类型不匹配,因此编译报错。
修复代码
将第36行的代码替换为以下内容,把布尔值转换为对应的 ErrorAttributeOptions 对象:
// 获取是否包含堆栈跟踪的布尔值 boolean includeStackTrace = isIncludeStackTrace(request, MediaType.APPLICATION.JSON); // 根据布尔值构建ErrorAttributeOptions ErrorAttributeOptions options = includeStackTrace ? ErrorAttributeOptions.of(ErrorAttributeOptions.Include.STACK_TRACE) : ErrorAttributeOptions.defaults(); // 调用getErrorAttributes方法 Map<String, Object> body = getErrorAttributes(request, options);
额外说明
ErrorAttributeOptions 是 Spring Boot 2.6+ 引入的增强类,支持更精细地控制错误响应中包含的属性(比如消息、堆栈、异常详情等)。除了 STACK_TRACE,你还可以根据需求添加其他选项,例如:
// 同时包含消息和堆栈跟踪 ErrorAttributeOptions options = ErrorAttributeOptions.of( ErrorAttributeOptions.Include.MESSAGE, ErrorAttributeOptions.Include.STACK_TRACE );
内容的提问来源于stack exchange,提问作者CodeLearner
相关产品推荐
相关产品推荐

