1 SpringBoot中对于异常处理提供了五种处理方式
1.1 自定义错误页面
1.2 @ExceptionHandle注解处理异常
1.3 @ControllerAdvice + @ExceptionHandle注解处理异常
1.4 配置SimpleMappingExceptionResolver处理异常
1.5 自定义HandleExceptionResolver类处理异常
2 创建项目
3 修改pom.xml:引入相应的启动器
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<groupId>com.bjsxt</groupId>
<artifactId>14-spring-boot-exception1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- springboot的web启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- springboot的thymeleaf启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
</project>
4 编码
4.1 controller类编写
/**
* SpringBoot处理异常方式一:自定义错误页面
*/
@Controller
public class DemoController {
@RequestMapping("/show")
public String showInfo() {
String str = null;
str.length(); //此处必会抛空指针异常
return "index";
}
}
4.2 创建index.html页面,随便的页面即可
4.3 编写启动类
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
4.4 启动测试:默认SpringBoot的异常处理的方式
5 SpringBoot默认的处理异常机制
SpringBoot默认的已经提供了一套处理异常的机制,一旦程序中出现了异常,SpringBoot会向/error的url发送请求。在SpringBoot中提供了一个叫BasicErrorController来处理/error请求,然后跳转到默认显示异常的页面来展示异常信息。如以下截图。但在实际中不太适用的。
6 改进(创建error.html)
注意:文件名称必须叫error,
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>错误提示页面</title>
</head>
<body>
出错了,请与管理员联系……
<span th:text="${exception}"></span>
</body>
</html>
7 改进后测试
但是拿不到错误信息,断点调试时发现DefaultErrorAttributes类中includeException字段一直都是false,导致没有将exception信息写入并返回,一直找不到如何解决这个问题。