SpringBoot2.x在线教育项⽬中⾥⾯的全局异常处理
简介:讲解SpringBoot2.X全局异常处理
为什么要配置全局异常?
- 不配全局服务端报错场景 1/0、空指针等
配置好处
- 统⼀的错误⻚⾯或者错误码
- 对⽤户更友好
Springboot2.X怎么在项⽬中配置全局异常
-
类添加注解
- @ControllerAdvice,如果需要返回json数据,则⽅法需要加@ResponseBody
- @RestControllerAdvice, 默认返回json数据,⽅法不需要加@ResponseBody
-
⽅法添加处理器
- 捕获全局异常,处理所有不可知的异常
- @ExceptionHandler(value=Exception.class)
controller层
@RestController
@RequestMapping("api/v1/test")
public class TestController {
@GetMapping("list")
public JsonData testExt(){
int i =1 /0;
return JsonData.buildSuccess("");
}
}
handle层
/**
* 标记这是一个异常处理
*/
@RestControllerAdvice //标记用于处理异常
//@ControllerAdvice
public class CustomExHandle {
//处理json
@ExceptionHandler(value = Exception.class)
Object handleException(Exception e, HttpServletRequest request){
return JsonData.buildError("服务端出问题",-2);
}
}
@RestControllerAdvice 和@ControllerAdvice 用于处理json和非json数据
SpringBoot2.x⾃定义全局异常返回页面
使⽤SpringBoot⾃定义异常和错误⻚⾯跳转实战
返回⾃定义异常界⾯,需要引⼊thymeleaf依赖(⾮必须,如果是简单的html界⾯则不⽤)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
创建error.html报错页面
html 页面
<!DOCTYPE html>
<!--在使用时需添加 xmlns:th="http://www/thymeleaf.org"-->
<html lang="en" xmlns:th="http://www/thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
这是一个自定义异常的界面
<!--获取到报错的信息 等,按需求获取所需的报错信息
注:msg必须与hanlde层中自定义的一致
e.getMessage() :报错的信息
e.getClass() :报错的类型
-->
<p th:text="${msg}"></p>
</body>
</html>
handle层
/**
* 标记这是一个异常处理
*/
//@RestControllerAdvice //标记用于处理异常
@ControllerAdvice
public class CustomExHandle {
// //处理json
// @ExceptionHandler(value = Exception.class)
// Object handleException(Exception e, HttpServletRequest request){
// return JsonData.buildError("服务端出问题",-2);
// }
@ExceptionHandler(value = Exception.class)
Object handleException(Exception e, HttpServletRequest request){
ModelAndView modelAndView =new ModelAndView();
modelAndView.setViewName("error.html");
modelAndView.addObject("msg",e.getMessage());
System.out.println(e.getMessage());
return modelAndView;
}
}