SpringBoot-全局异常处理1.0

1.为什么要使用全局异常处理器?

    为了避免在项目中频繁使用try cathch来捕获异常,我们可用通过一个全局异常处理进行捕获异常和自定义异常。Validator校验器抛出的异常,try catch也无法捕获,所以也需要用到全局异常处理器。

2.实现

2.1 首先需要编写一个用于返回给前端的Result类

public class Result implements Serializable {
    private int code; // 200是正常,非200表示异常
    private String msg;
    private Object data;

    //在只有数据的情况下默认为200
    public static Result succ(Object data) {
        return succ(200, "操作成功", data);
    }

    public static Result succ(int code, String msg, Object data) {
        Result r = new Result();
        r.setCode(code);
        r.setMsg(msg);
        r.setData(data);
        return r;
    }
    public static Result fail(String msg) {
        return fail(400, msg, null);
    }

    public static Result fail(String msg, Object data) {
        return fail(400, msg, data);
    }

    public static Result fail(int code, String msg, Object data) {
        Result r = new Result();
        r.setCode(code);
        r.setMsg(msg);
        r.setData(data);
        return r;
    }
}

2.2 自定义一个异常类,方法中的message参数用于传递给父类RuntimeException.

public class BusinessException extends RuntimeException{
    private int code;

    private String description;

    public BusinessException(String message, int code, String description) {
        super(message);
        this.code = code;
        this.description=description;
    }
    public BusinessException(R r, String description) {
        super(r.getMsg());
        this.code = r.getCode();
        this.description=description;
    }

}

2.3 编写全局异常处理类

@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody       //有方法需要返回json数据
@Slf4j
public class GlobalExceptionHandler {

     //指定捕获的异常类
    @ExceptionHandler(BusinessException.class)
    public Result exceptionHandler (BusinessException e){
       log.error(e.getMessage());
      
      //将异常类的信息封装成Result类,返回前端
       return Result.fail(e.getCode(),e.getMessage(),e.getDescription());
    }
}

2.4 ServiceImpl实现

业务代码没问题就直接返回Result.succ()

出现问题就抛出自定义异常,由全局异常处理器进行捕获封装成Result.fail()发送给前端。

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
    @Override
    public Result aa(String msg) {
        if (msg.equals("1")){
            return Result.succ("提交信息成功");
        }else
            throw new BusinessException("提交失败",400,"未提交信息");
    }
}


2.5 Controller实现

Controller中返回的只有请求成功的Result


@RestController
public class ExceptionController {

    @Autowired
    EmployeeService employeeService;

    @RequestMapping("/e")
    public Result e(@RequestParam(required = false,defaultValue = "1") String s){
        Result result = employeeService.aa(s);
        System.out.println(result);
        return result;
    }
}


posted @   别停  阅读(47)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示