自定义异常数据
@Bean
@ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
public DefaultErrorAttributes errorAttributes() {
return new DefaultErrorAttributes();
}
以上这一段源代码的意思是,如果存在ErrorAttributes类则使用本来存在的类,不存在就使用默认的DefaultErrorAttributes类来定义异常数据,所以要自定义就需要继承DefaultErrorAttributes 类来定制自己的类
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
Map<String, Object> map = super.getErrorAttributes(webRequest, options);
if((Integer) map.get("status")==404){
map.put("message","找不到页面");
}
return map;
}
}
前端页面:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>404Title</title>
</head>
<body>
<table border="1" align="solid">
<tr>
<td>path</td>
<td th:text="${path}"></td>
</tr>
<tr>
<td>error</td>
<td th:text="${error}"></td>
</tr>
<tr>
<td>message</td>
<td th:text="${message}"></td>
</tr>
<tr>
<td>timestamp</td>
<td th:text="${timestamp}"></td>
</tr>
<tr>
<td>status</td>
<td th:text="${status}"></td>
</tr>
</table>
</body>
</html>
结果:
自定义异常页面
如果存在ErrorViewResolver类则使用本来存在的类,不存在就使用默认的DefaultErrorViewResolver类来定义异常数据,所以要自定义就需要继承DefaultErrorViewResolver类来定制自己的类来返回错误页面
自定义类:
@Component
public class MyErrorViewResolver extends DefaultErrorViewResolver {
public MyErrorViewResolver(ApplicationContext applicationContext, WebProperties.Resources resources) {
super(applicationContext, resources);
}
@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
Map<String,Object> map = new HashMap<>();
if((Integer) model.get("status") == 500){
map.putAll(model);
map.put("message","服务器端出现错误");
}
ModelAndView view = new ModelAndView("dong/521", map);
return view;
}
}
前端页面:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>404Title</title>
</head>
<body>
<h1>521.html</h1>
<table border="1" align="solid">
<tr>
<td>path</td>
<td th:text="${path}"></td>
</tr>
<tr>
<td>error</td>
<td th:text="${error}"></td>
</tr>
<tr>
<td>message</td>
<td th:text="${message}"></td>
</tr>
<tr>
<td>timestamp</td>
<td th:text="${timestamp}"></td>
</tr>
<tr>
<td>status</td>
<td th:text="${status}"></td>
</tr>
</table>
</body>
</html>
|