统一异常处理类
//下面注解表示当前类是用于处理控制器增强功能的
// 这里的控制器增强功能指控制器方法中出现的异常,本类来统一处理
@RestControllerAdvice
public class GlobalExceptionHandler {
//下面注解表示紧随的方法是处理控制器发送的异常的
@ExceptionHandler(Exception.class)
@ResponseBody
public R error(Exception e){
e.printStackTrace();
return R.error().message("执行了统一异常处理..");
}
@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public R error(ArithmeticException e){
e.printStackTrace();
return R.error().message("执行了ArithmeticException异常处理..");
}
//自定义传异常
@ExceptionHandler(GuliException.class)
@ResponseBody
public R error(GuliException e){
e.printStackTrace();
return R.error().code(e.getCode()).message(e.getMsg());
}
}
自定义异常类
@Data
@AllArgsConstructor //有参构造
@NoArgsConstructor //无参构造
public class GuliException extends RuntimeException{
private Integer code;
private String msg;
}
调用
try {
int a = 1/0;
}catch (Exception e){
throw new GuliException(20001,"执行了自定义异常..");
}