且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SpringBoot 统一异常处理\统一响应报文\自定义异常

更新时间:2022-04-15 02:55:58

SpringBoot 统一异常处理

使用注解 @ControllerAdvice

自定义异常

package com.manlitech.cloudboot.basebootconfig.exception;

import com.manlitech.cloudboot.common.enums.ResultEnums;

public class MyException extends RuntimeException{
private Integer code;

    public MyException(ResultEnums resultEnum) {
        super(resultEnum.getMsg());
        this.code = resultEnum.getCode();
    }

    public MyException(Integer code,String msg) {
        super(msg);
        this.code = code;
    }

    public Integer getCode() {
        return code;
    }

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

}

异常捕获做处理

package com.manlitech.cloudboot.basebootconfig.exception;

@ControllerAdvice
@Component
public class ExceptionHandle {

    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
    
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception e) {
        //logger.error("exceptionmsg="+e.getMessage());
        if (e instanceof MyException) {
            MyException myException = (MyException) e;
            return ResultUtil.error(myException.getCode(), myException.getMessage());
        }else {
            //logger.error("【系统异常】"+e.getStackTrace());
            e.printStackTrace();
            String message = getExceptionToString(e);
            // 可能由于运行是sentinel发出的runtimeException
            Result sentinelResult = ExceptionHandle.isSentinelRuntimeException(message);
            if(sentinelResult != null){
                return sentinelResult;
            }
            return ResultUtil.error(ResultEnums.UNKONW_ERROR.getCode(),ResultEnums.UNKONW_ERROR.getMsg(),message);
        }
    }


}

ResultUtil 响应公用的方法

package com.manlitech.cloudboot.common.utils;


import org.joda.time.DateTime;

import java.util.List;

public class ResultUtil {

    public static Result success(Object object) {
        Result result = new Result();
        result.setCode(0);
        result.setMsg("成功");
        result.setData(object);
        result.setSystemTime(DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
        return result;
    }

    public static Result success(Integer code , String msg) {
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        result.setSystemTime(DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
        return result;
    }

    public static Result success(List list,Long total) {
        Result result = new Result();
        result.setCode(0);
        result.setMsg("成功");
        result.setData(list);
        result.setRows(total);
        result.setSystemTime(DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
        return result;
    }

    public static Result success() {
        return success(null);
    }

    public static Result error(Integer code, String msg) {
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        result.setSystemTime(DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
        return result;
    }
    
    public static Result error(Integer code, String msg ,Object object) {
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        result.setData(object);
        result.setSystemTime(DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
        return result;
    }
}

统一的响应格式

package com.manlitech.cloudboot.common.utils;

public class Result<T> {

    /** 错误码. */
    private Integer code;

    /** 提示信息. */
    private String msg;

    /** 具体的内容. */
    private T data;

    /** 错误码. */
    private Long rows;
    
    /** 当前系统时间 */
    private String systemTime;

    public Long getRows() {
        return rows;
    }

    public void setRows(Long rows) {
        this.rows = rows;
    }

    public Integer getCode() {
        return code;
    }

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

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getSystemTime() {
        return systemTime;
    }

    public void setSystemTime(String systemTime) {
        this.systemTime = systemTime;
    }


}

统一的字典码

package com.manlitech.cloudboot.common.enums;

public enum ResultEnums {

    /*成功返回*/
    SUCCESS(0, "成功"),
    SUCCESS_LOGOUT(1, "退出成功,期待下次使用本系统"),
    /*特殊异常*/
    UNKONW_ERROR(-1, "呀,服务器开小差了~"),
    //登录相关
    NO_LOGIN(-2,"用户信息不存在。可能未登录"), 
    NO_LOGIN_ERR_LOGIN_Info(-3,"用户名密码错误或信息不存在,请核对"),
    NO_LOGIN_REFRESH_TOKEN_IS_EXPIRE(-4,"refresh_token已经失效"),
    ERROR_TOKEN(-5,"token验证失败"),
    ERROR_PERMISSION(-6,"无访问权限"),
    /* 异常相关 */
    UNKONW_REDIS_TYPE(-7,"redis类型[单机,集群]未知"),
    SQL_INJECTION(-8,"警告:sql存在注入风险"),
    NO_FOUND_QUEUE_NAME_JOB (-9,"未找到相对应的队列名称"),
    ERROR_GATEWAY (-10,"网关异常提示"),
    API_FLOW_EXCEPTION (-11,"服务繁忙,请重试,服务限流") ,
    API_DEGRADE_EXCEPTION(-12,"服务繁忙,请重试,服务降级"),
    API_PARAM_HOT_FLOW_EXCEPTION(-13,"服务繁忙,请重试,热点参数限流"),
    API_SYSTEM_BLOCK_EXCEPTION(-14,"服务繁忙,请重试,系统规则(负载/...不满足要求)"),
    API_AUTHORITY_EXCEPTION(-15,"授权规则不通过");
    private Integer code;

    private String msg;

    ResultEnums(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Integer getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }
}

微信公众号,需要的话就关注下我~

SpringBoot 统一异常处理\统一响应报文\自定义异常