全局异常处理
@ControllerAdvice
:用于捕获全局异常
@ExceptionHandler
:传入指定异常类
@ControllerAdvice
public class GlobalExceptionHandler {
//指定什么异常执行该方法(Exception:所有异常)
@ExceptionHandler(Exception.class)
@ResponseBody
public R error(Exception e) {
e.printStackTrace();
return R.error().message("执行了全局异常");
}
}
特定异常处理
//指定什么异常执行该方法(Exception:所有异常)
@ExceptionHandler(ArithmeticException.class) //此处指定异常类型
@ResponseBody
public R error(ArithmeticException e) {
e.printStackTrace();
return R.error().message("特定异常处理");
}
自定义异常处理
1、指定错误码与错误信息类
public enum TeacherError {
E_10001(10001, "添加教师出现重复信息"),
E_10002(10002, "更新教师出现重复信息");
private Integer code;
private String msg;
TeacherError(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
2、创建一个自定义异常类继承RuntimeException
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GuliException extends RuntimeException {
private Integer code; //异常状态码
private String msg; //异常信息
}
3、将自定义异常类传入全局异中
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(GuliException.class)
@ResponseBody
public R error(GuliException e) {
e.printStackTrace();
return R.error().code(e.getCode()).message(e.getMsg());
}
}
演示
throw new GuliException(TeacherError.E_10001.getCode(),TeacherError.E_10001.getMsg());