尝试自己定义异常捕获,不一定完全正确,但确实可用
创建自定义的错误码类型,使用枚举类ExceptionType
public enum ExceptionType {
INNER_ERROR(500,"我不想处理的错误"),
UNAUTHORIZED(401,"未登录"),
BAD_REQUEST(400,"请求错误"),
FORBIDDEN(403,"无权操作"),
NOT_FOUND(404,"未找到"),
USER_NAME_DUPLICATE(40001001,"用户名重复"),
USER_NOT_FOUND(40401001,"用户名不存在");
private final Integer code;
private final String message;
ExceptionType(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer getCode() {
return code;
}
public String getMessage() {
return message;
}
}
创建自定义的异常捕获类型 BizException,继承 RuntimeException,之后可以将这个类的实例throw
需要重载构造函数,传入枚举类ExceptionType,使用枚举类的getMessage方法
public class BizException extends RuntimeException{
private final Integer code;
public BizException(ExceptionType exceptionType) {
super(exceptionType.getMessage());
this.code = exceptionType.getCode();
}
public Integer getCode(){
return code;
}
}
使用,在try…catch…中throw实例即可
try {
// ...业务代码
} catch (IOException e) {
e.printStackTrace();
throw new BizException(ExceptionType.FORBIDDEN);
}



