- 创建SpringBoot工程,导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- 编写异常类
//如果希望对所有的异常进行统一的处理,比如当指定的异常发生时,把它映射到要显示的错误的网页中,此时用SimpleMappingExceptionResolver进行解析
@Configuration
public class MyException03 {
@Bean
SimpleMappingExceptionResolver simpleMappingExceptionResolver() {
SimpleMappingExceptionResolver simpleMappingExceptionResolver = new SimpleMappingExceptionResolver();
Properties mapping = new Properties();
mapping.put("java.lang.ArithmeticException", "error");
simpleMappingExceptionResolver.setExceptionMappings(mapping);
return simpleMappingExceptionResolver;
}
}
- 编写HTML文件,异常显示页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>异常页面</title>
</head>
<body>
<div th:text="${error}"></div>
<h1>异常页面</h1>
</body>
</html>
- 测试
@RestController
public class HelloController {
@GetMapping("/hello")
public void hello(){
int i=1/0;
}
}
成功!