一. 问题背景
自己定制一个Exception类继承RuntimeException,但是错误页面却获取不到${exception}
二. 解决方案
2.1 解决步骤
- 在application.properties配置如下:
#获取SpringBoot的异常对象exception
server.error.include-exception=true
- 重启程序编译运行即可
2.2 原理
错误页面的异常信息都是在DefaultErrorAttributes类中进行封装的,它有一个属性是includeException并且默认值是false,在封装exception对象的时候,它通过判断includeException是否为true来决定是否封装,如下:
private final boolean includeException;
public DefaultErrorAttributes() {
this(false);
}
...
if (this.includeException) {//由于这里为false,所以exception对象没有被put到errorAttributes(它是一个Map)中
errorAttributes.put("exception", error.getClass().getName());
}
因此在application.properties配置文件配置server.error.include-exception=true
将includeException改成true即可
SpringBoot错误页面原理可参考博客:Day41——错误处理原理&定制错误页面