主要思路
通过继承默认异常属性类 DefaultErrorAttributes
,并重写其中的getErrorAttributes
,就能实现自定义异常数据
如下:
@Component
public class MyErrorAttribute extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
Map<String, Object> map = super.getErrorAttributes(webRequest, includeStackTrace);
map.put("myerror","这是我的异常信息");
return map;
}
}
然后再在 templates 目录的下的错误页面中 注册myerror
:
自定义错误页面,参考链接:https://www.cnblogs.com/youcoding/p/13186489.html
如下是 5xx.html
的完整代码:
<!DOCTYPE html>
<html lang="en" xmlns:th="www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>
template 5xx
</h1>
<table border="1">
<tr>
<td>path</td>
<td th:text="${path}"></td>
</tr>
<tr>
<td>timestamp</td>
<td th:text="${timestamp}"></td>
</tr>
<tr>
<td>message</td>
<td th:text="${message}"></td>
</tr>
<tr>
<td>error</td>
<td th:text="${error}"></td>
</tr>
<tr>
<td>status</td>
<td th:text="${status}"></td>
</tr>
<tr>
<td>myerror</td>
<td th:text="${myerror}"></td>
</tr>
</table>
</body>
运行如下:
每天学习一点点,每天进步一点点。