SpringBoot基础教程(十二) | 异常篇
背景
不管是自己写程序练习还是实际项目开发中,我们总会遇到各种各样的异常情况,比如Java中的NullPointerException,IOException等等;为了处理这些异常,经常需要许多try,catch语句,使程序中出现了很多重复的代码;而SpringBoot就可以通过简单的配置,全局管理异常,极大的简化了异常处理。
引入依赖
这里我们引入web和thymeleaf模块,因为项目中一般出现异常后,都会携带错误信息跳转到Error界面
<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>编写异常界面
接下来我们在src/resources/templates文件夹下新建一个Error.html用于展示错误信息
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.html.org">
<head>
<meta charset="UTF-8">
<title>myErrorPage</title>
</head>
<body>
<h2>异常界面</h2>
<table>
<tr>
<td>异常信息:</td>
<td th:text="${errMsg}"></td>
</tr>
<tr>
<td>时间戳:</td>
<td th:text="${timestamp}"></td>
</tr>
<tr>
<td>错误码:</td>
<td th:text="${status}"></td>
</tr>
<tr>
<td>路径:</td>
<td th:text="${url}"></td>
</tr>
</table>
</body>
</html>编写异常配置类
接下来我们新建一个ExceptionConfig.java,用来编写全局异常的控制类。
/**
* 全局异常配置类
*/
@RestControllerAdvice
public class ExceptionConfig{
/**
* 捕获运行时异常,并跳转到自定义的Error界面
*/
@ExceptionHandler(value = RuntimeException.class)
public ModelAndView defaultException(HttpServletRequest request,RuntimeException e,HttpServletResponse response){
Map<String,Object> returnMap = new HashMap<>();
returnMap.put("errMsg",e.getMessage());
returnMap.put("timestamp",System.currentTimeMillis());
returnMap.put("status",response.getStatus());
returnMap.put("url",request.getRequestURL());
ModelAndView modelAndView = new ModelAndView("Error",returnMap);
return modelAndView;
}
}- @RestControllerAdvice:相当于@ControllerAdvice与@ResponseBody的结合体,@ControllerAdvice是用于捕获controller抛出的异常的。
- @ExceptionHandler:用于标识要捕获的异常类型,这里我们捕获所有运行时异常,实际项目中,我们一般会粒度更细的捕获异常,返回不同的异常信息。
编写控制器
这里为了测试需要,随便制造一个运行时异常。
@RestController
public class ExceptionController{
/**
* 测试运行时异常,并跳转异常页面
*/
@GetMapping(value = "/testRuntimeException")
public int testDefaultException(){
String test = "x";
return Integer.parseInt(test);
}
}测试
启动项目,打开浏览器后输入http://localhost:8080/testRuntimeException,就可以看到效果了。
