为什么要配置全局异常? 不配全局服务端报错场景 1/0、空指针等 配置好处 统⼀的错误⻚⾯或者错误码 对⽤户更友好
Springboot2.X怎么在项⽬中配置全局异常 类添加注解
@ControllerAdvice,如果需要返回json数据,则⽅法需要加@ResponseBody
@RestControllerAdvice, 默认返回json数据,⽅法不需要加@ResponseBody ⽅法添加处理器
捕获全局异常,处理所有不可知的异常 @ExceptionHandler(value=Exception.class)
1/0 肯定会报错,如果这个时候用postman去访问这个接口,报错会很复杂,一般是看不懂,所以要改成用户能看懂的样子
@GetMapping("list")
public JsonData testExt(){
int i = 1/0;
return JsonData.buildSuccess("");
}
方法一:加一个handler包,建一个CustomExtHandler.java
原理是获取到所有的异常清况,然后返回你想输出的json格式
package net.xdclass.demoproject.handler;
import net.xdclass.demoproject.utils.JsonData;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
/**
* 标记这个是一个异常处理类
*/
@RestControllerAdvice
public class CustomExtHandler {
@ExceptionHandler(value = Exception.class)
JsonData handlerException(Exception e, HttpServletRequest request){
return JsonData.buildError("服务端出问题了", -2);
}
}
方法二:自定义返回新页面
package net.xdclass.demoproject.handler;
import net.xdclass.demoproject.utils.JsonData;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
/**
* 标记这个是一个异常处理类
*/
//@RestControllerAdvice
@ControllerAdvice
public class CustomExtHandler {
//
// @ExceptionHandler(value = Exception.class)
// JsonData handlerException(Exception e, HttpServletRequest request){
//
// return JsonData.buildError("服务端出问题了", -2);
// }
@ExceptionHandler(value = Exception.class)
Object handlerException(Exception e, HttpServletRequest request){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error.html");
System.out.println(e.getMessage());
modelAndView.addObject("msg",e.getMessage());
return modelAndView;
}
}
error.html:
<!DOCTYPE html>
<html xmlns:th="http://www/thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
欢迎来到小滴课堂学习 这个是自定义异常界面
<p th:text="${msg}"> </p>
</body>
</html>