- 定义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
@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;
}
}
- 全局异常处理类
@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;
}
}
- 抛出异常
throw new UnLoginException()
通过以上4个步骤,就可实现抛出异常时修改http状态码,主要用在前后端分离时,前端根据状态吗进行页面跳转。
|