springboot自定义全局异常处理+前台返回异常统一处理

一、思想

第一步、定义一个返回类型枚举rescode,返回类res(rescode)

第二步、自定义运行时异常类bussEx ,定义全局异常处理类GolbEx

第三步、判断返回前端是否出现异常

               3.1出现异常:手动抛出bussEx(rescode),并传入错误类型,会触发GolbEx类中关联bussEx的方法handler(ex),在

                    handler()中取出code和info,封装到res返回类,返回给前端

               3.2未出现异常:直接control层返回封装好数据的res对象

其实说白了,最终都是返回res对象,只是一个是在control层直接返回,一个是在全局异常处理类中捕获异常,然后返回;而rescode枚举类也只是为了封装状态类型,即使没有这个枚举,也可以实现标题功能

 

二、代码

//返回类模板

public class ResTypeBean {
    private int code;
    private String info;
    private T data;


    public ResTypeBean(){};
    public ResTypeBean(int code,String info){
        this.code = code;
        this.info = info;
    }
    public ResTypeBean(int code,String info,T data){
        this.code = code;
        this.info = info;
        this.data = data;
    };

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}
//返回类型枚举,可扩展

public enum  ResCode {
    SUCCESS(0,"成功"),
    UNKNOWN(-1,"未知错误");

    private int code;
    private String info;

    ResCode(int code,String info){
     this.code = code;
     this.info = info;
    }

    public int getCode() {
        return code;
    }

    public String getInfo() {
        return info;
    }
}

//自定义运行时异常
public class BusinessException extends RuntimeException{
    private int errCode = ResCode.UNKNOWN.getCode();

    public BusinessException(){};
    public BusinessException(ResCode resCode){
        super(resCode.getInfo());
        this.errCode = resCode.getCode();
    }

    public int getErrCode() {
        return errCode;
    }

    public void setErrCode(int errCode) {
        this.errCode = errCode;
    }
}

//全局异常处理类
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = BusinessException.class)
    public ResTypeBean businessExceptionHandler(BusinessException e) throws  Exception{
        ResTypeBean res = new ResTypeBean<>(e.getErrCode(), e.getMessage());
        return res;
    }
}
 
  

测试代码

    @RequestMapping(value = "/getDicList" ,method = RequestMethod.POST)
    public ResTypeBean getDicList(){
        if(错误){
            new BusinessException(ResCode.UNKNOWN);
        }else{
            DicListBean dicList = dataService.getDicList();
            return new ResTypeBean(ResCode.SUCCESS.getCode(),ResCode.SUCCESS.getInfo(),dicList); 
        }
//        DicListBean dicList = dataService.getDicList();
//        return new ResTypeBean(ResCode.SUCCESS.getCode(),ResCode.SUCCESS.getInfo(),dicList);
    }

 

你可能感兴趣的:(java)