@Data
@AllArgsConstructor//有参构造
@NoArgsConstructor //无参构造
public class GuliException extends RuntimeException {
private Integer code;//状态码
private String msg;//异常信息
}
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
//指定出现什么异常执行这个任务
//全局异常处理
@ExceptionHandler(Exception.class)
public R error(Exception e){
e.printStackTrace();
return R.error().message("执行了全局异常处理");
}
//特定异常处理
@ExceptionHandler(ArithmeticException.class)
public R ArithmeticException(ArithmeticException e){
e.printStackTrace();
return R.error().message("执行了ArithmeticException异常处理");
}
//自定义异常处理
@ExceptionHandler(GuliException.class)
public R GuliException(GuliException e){
//把錯誤信息写到错误日志里面去
log.error(e.getMessage());
e.printStackTrace();
return R.error().code(e.getCode()).message(e.getMsg());
}
}