- 全局异常
- 特定异常
- 自定义异常
1. 全局异常处理
创建类GlobalExceptionHandler
package com.atguigu.service_base.config.handler;
import com.atguigu.common_utils.ExceptionUtil;
import com.atguigu.common_utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
//指定出现什么异常执行这个方法
@ExceptionHandler(Exception.class)
@ResponseBody //为了返回数据
public Result error(Exception e) {
e.printStackTrace();
return Result.error().message("网络异常,请重试..");
}
//特定异常
@ExceptionHandler(ArithmeticException.class)
@ResponseBody //为了返回数据
public Result error(ArithmeticException e) {
e.printStackTrace();
return Result.error().message("执行了ArithmeticException异常处理..");
}
//自定义异常
@ExceptionHandler(GuliException.class)
@ResponseBody //为了返回数据
public Result error(GuliException e) {
//这块用到了日志处理的异常工具打印
log.error(ExceptionUtil.getExceptionMessage(e));
e.printStackTrace();
return Result.error().code(e.getCode()).message(e.getMsg());
}
}
2. 自定义异常
创建类 GuliException 集成 RuntimeException
@Data
@AllArgsConstructor //生成有参数构造方法
@NoArgsConstructor //生成无参数构造
public class GuliException extends RuntimeException {
private Integer code;//状态码
private String msg;//异常信息
}
用 @ExceptionHandler(GuliException.class) 捕获并处理