什么是统一异常处理
1.首先制造异常
除零异常
int i=10/0;
在前端的显示
//服务器内部错误
{
"timestamp": "2021-05-29 20:50:00",
"status": 500,
"error": "Internal Server Error",
"message": "/ by zero",
"path": "/eduservice/edu-teacher/findAll"
}
什么是统一异常处理
我们想让异常结果也显示为统一的返回结果对象,并且统一处理系统的异常信息,那么需要统一异常处理。
统一异常处理
1、创建统一异常处理器
创建统一异常处理类GlobalExceptionHandler.java:
@ControllerAdvice //使用 @ControllerAdvice 实现全局异常处理
@Slf4j
public class GlobaExceptionHandler {
@ExceptionHandler(Exception.class)// 全局异常 加入Exception 都会执行这个
@ResponseBody //数据返回 json
public R error(Exception e){
e.printStackTrace();
return R.error().message("执行全局异常处理~~~~~~~~~~~~~~");
}
}
返回结果
{
"success": false,
"code": 20001,
"message": "执行全局异常处理~~~~~~~~~~~~~~",
"data": {}
}
2. 处理特定异常
1、添加异常处理方法
GlobalExceptionHandler.java中添加
/*
特定异常处理 算数计算异常
*/
@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public R error(ArithmeticException e){
e.printStackTrace();
return R.error().message("执行了特定异常处理");
}
返回结果(优先于全局异常 )
{
"success": false,
"code": 20001,
"message": "执行了特定异常处理 ArithmeticException",
"data": {}
}
3.自定义异常
1、创建自定义异常类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GuliException extends RuntimeException {
@ApiModelProperty(value = "状态码")
private Integer code;
@ApiModelProperty(value = "描述异常信息")
private String msg;
@Override
public String toString() {
return "GuliException{" +
"message=" + this.getMessage() +
", code=" + code +
'}';
}
}
2、添加异常处理方法
GlobalExceptionHandler.java中添加
/**
*
* @param e 自定义异常处理
* @return
*/
@ExceptionHandler(GuliException.class)
@ResponseBody
public R error(GuliException e){
e.printStackTrace();
return R.error().message(e.getMsg()).code(e.getCode());
}
3.调用自定义异常类
//调用自定义异常
try {
int i=10;
} catch (Exception e) {
throw new GuliException(20001,"出现自定义异常");
}
返回结果
{
"success": false,
"code": 20001,
"message": "出现自定义异常",
"data": {}
}