springboot异常
通用类异常配置,这里使用thymeleaf 作为视图模板,所以在pom 文件中需要添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
创建自定义异常类, MyExceptionAttributes 实现DefaultErrorAttributes 接口
/**
* @Author :lx
* @Date :Create in 17:07 2021/10/26
*配置自定义的异常 提示
**/
@Component
public class MyExceptionAttributes extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, ErrorAttributeOptions.of(
ErrorAttributeOptions.Include.EXCEPTION,
ErrorAttributeOptions.Include.BINDING_ERRORS,
ErrorAttributeOptions.Include.EXCEPTION,
ErrorAttributeOptions.Include.MESSAGE,
ErrorAttributeOptions.Include.STACK_TRACE));
//errorAttributes 这个map 放了异常提示,可对它进行覆盖修改以及添加
errorAttributes.put("message","你访问的页面出现了异常");
errorAttributes.put("type","自定义异常显示");
return errorAttributes;
}
创建自定义异常视图解析类 MyExceptionResolverView 实现DefaultErrorViewResolver 接口
/**
* @Author :lx
* @Date :Create in 17:04 2021/10/26
* 自定义异常视图处理类,可告知springboot将出现的异常页面转给相应的视图处理
**/
@Component
public class MyExceptionResolverView extends DefaultErrorViewResolver {
public MyExceptionResolverView(ApplicationContext applicationContext, WebProperties.Resources resources) {
super(applicationContext, resources);
}
@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
//将异常转到给templates目录下的error文件夹下的error.html处理
return new ModelAndView("error/error",model);
}
}
创建controller 演示出现异常的情况
@Controller
public class HelloController {
String a;
@RequestMapping("/hello1")
@ResponseBody
public String exceptionTest1() {
System.out.println(123);
a.equals(11);
return "null point";
}
@RequestMapping("/hello2")
@ResponseBody
public String exceptionTest2() {
int i = 1 / 0;
return "null point";
}
@RequestMapping("/hello3")
public String exceptionTest3() {
System.out.println("fangwen bucunzaideyemian");
return "null point";
}
error.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
error html
<div>
<table border="1">
<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>path</td>
<td th:text="${path}"></td>
</tr>
<tr>
<td>trace</td>
<td th:text="${trace}"></td>
</tr>
<tr>
<td>exception</td>
<td th:text="${exception}"></td>
</tr>
<tr>
<td>status</td>
<td th:text="${status}"></td>
</tr>
<tr>
<td>type</td>
<td th:text="${type}"></td>
</tr>
</table>
</div>
</body>
</html>
项目运行结果以及项目结构