springboot自定义错误响应时获取不到exception对象
2.x版本以上在application.properties需要中添加以下代码
#开启自定义异常处理
server.error.include-exception=true
当添加以上代码任然获取不到exception对象时,在自定义的ErrorAttribute方法中添加一个无参构造,调用父类方法并设置为true
@Component
public class MyErrorAttribute extends DefaultErrorAttributes {
public MyErrorAttribute() {
super(true);
}
}
追踪DefaultErrorAttributes的代码
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DefaultErrorAttributes implements ErrorAttributes, HandlerExceptionResolver, Ordered {
/**
* Create a new {@link DefaultErrorAttributes} instance that does not include the
* "exception" attribute.
*/
public DefaultErrorAttributes() {
this(false);//includeException默认为false
}
}