1. 定义ErrCode
**
 * 错误码 枚举
 */
public enum ErrCode {

    /**
     * 系统错误
     */
    SYSTEM_ERROR(1000, "系统错误"),

    /**
     * 参数错误
     */
    PARAMETER_ERROR(1001, "参数错误"),

    /**
     * 参数错误
     */
    NOT_NULL_ERROR(1002, "参数不能为空"),

    /**
     * 文件类型错误
     */
    FILE_TYPE_ERROR(1003, "文件类型错误"),

    /**
     * 数据不存在
     */
    DATA_IS_EMPTY(1004, "数据不存在"),

    PERMIT_FAIL(400401, "没有相关权限"),

    UNLOGIN(401, "未登录"),

    /**
     * 操作失败,一般用于修改删除,没有成功
     */
    FAIL(1004, "操作失败");


    Integer code;
    String msg;

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

    public static final Map<Integer, String> ERR_CODE = new HashMap<>();

    static {
        for (ErrCode errCode : ErrCode.values()) {
            ERR_CODE.put(errCode.getCode(), errCode.getMsg());
        }
    }

    public String getMsg() {
        return msg;
    }

    public Integer getCode() {
        return code;
    }

    public static String getMsg(Integer code) {
        String msg = ERR_CODE.get(code);
        if (!StringUtils.isEmpty(msg)) {
            return msg;
        }
        return null;
    }
}

1、定义Exception

/**
 * @author lyl
 */
@Slf4j
public class UnLoginException extends RuntimeException {
    @Getter
    private Integer code = 401;
    @Getter
    private String message;
    @Getter
    private Object data;

    public UnLoginException() {
        this(ErrCode.UNLOGIN.getCode(), ErrCode.UNLOGIN.getMsg(), null);
    }

    public UnLoginException(Object data) {
        this(ErrCode.UNLOGIN.getCode(), ErrCode.UNLOGIN.getMsg(), data);
    }


    public UnLoginException(int code, String message, Object data) {
        if (code == 0) {
            throw new RuntimeException("0 are not allowed to set !");
        }
        this.code = code;
        this.message = message;
        this.data = data;
    }
}
  1. 全局异常处理类
/**
 * @author lyl
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ResponseStatus(HttpStatus.UNAUTHORIZED) // 这里非常关键,这是修改的状态吗
    @ExceptionHandler(UnLoginException.class)
    public Res unloginExceptionHandler(UnLoginException e) {
        log.error("An " + e.getClass().getName() + " occurs :{}", e);
        Res res = new Res(e.getCode(), e.getMessage(), e.getData());
        return res;
    }
}
  1. 抛出异常
throw new UnLoginException()

通过以上4个步骤,就可实现抛出异常时修改http状态码,主要用在前后端分离时,前端根据状态吗进行页面跳转。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐