Spring Boot 2升级后未传trace参数仍返回堆栈跟踪问题
看起来你遇到了Spring Boot 1.5.x到2.0.x升级后错误处理行为不一致的问题,我来帮你梳理下原因和解决办法:
问题根源分析
你配置的server.error.include-stacktrace=on-trace-param在Spring Boot 2.0.x中的预期行为是:仅当请求URL中携带trace=true参数时,才返回堆栈跟踪信息;无参数或参数为trace=false/其他无效值时,都不返回堆栈。但你遇到的情况正好相反——无参数时返回堆栈,只有trace=false时才隐藏,这大概率是Spring Boot 2.0.1版本的一个小bug(该版本是2.0系列的早期版本,存在一些未修复的问题),或者是默认错误处理逻辑的行为差异导致的。
具体解决办法
1. 优先升级到2.0.x系列的稳定版本
Spring Boot 2.0.1发布于2018年,后续的2.0.9.RELEASE(该系列最后一个稳定版)修复了不少早期的bug。建议你把版本升级到2.0.9.RELEASE,很多情况下这类配置不生效的问题会直接解决。修改你的pom.xml(Maven)或build.gradle(Gradle)中的Spring Boot版本即可:
Maven示例:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent>
Gradle示例:
plugins { id 'org.springframework.boot' version '2.0.9.RELEASE' id 'java' }
2. 自定义ErrorAttributes强制控制堆栈显示
如果暂时无法升级版本,可以通过自定义ErrorAttributes来覆盖默认逻辑,确保严格按照trace参数的值来决定是否返回堆栈:
首先创建自定义的ErrorAttributes实现类:
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes; import org.springframework.web.context.request.WebRequest; import java.util.Map; public class TraceControlledErrorAttributes extends DefaultErrorAttributes { @Override public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) { // 手动判断trace参数:仅当参数为"true"时才返回堆栈 String traceParam = webRequest.getParameter("trace"); boolean shouldInclude = "true".equalsIgnoreCase(traceParam); return super.getErrorAttributes(webRequest, shouldInclude); } }
然后在配置类中注册这个Bean:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ErrorHandlingConfig { @Bean public TraceControlledErrorAttributes traceControlledErrorAttributes() { return new TraceControlledErrorAttributes(); } }
这个自定义实现会完全忽略Spring Boot默认的includeStackTrace参数传递,而是严格根据trace参数的值来决定是否包含堆栈信息,彻底解决配置不生效的问题。
3. 检查配置加载情况
先确认你的server.error.include-stacktrace=on-trace-param配置确实被正确加载了:
- 启动应用时,在日志中搜索
server.error.include-stacktrace,查看是否输出了正确的配置值on-trace-param; - 如果日志中没有这个配置项,检查你的
application.properties是否放在正确的位置(默认是src/main/resources下),或者是否有其他配置文件(比如application-dev.properties)覆盖了这个配置。
内容的提问来源于stack exchange,提问作者gigi.com

