以字符串形式抛异常
枚举
package 包名路径.enums;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* @author 孙永潮
* @date 2022/12/21
*/
@ApiModel("异常错误状态码")
public enum ErrorEnums {
@ApiModelProperty("该用户不存在")
NO_USER_ERROR(-100, "该用户不存在"),
@ApiModelProperty("账号或密码错误")
LOGIN_ERROR(-101, "账号或密码错误"),
@ApiModelProperty("该用户已被冻结(封禁)")
USER_FREEZE_ERROR(-102, "该用户已被冻结(封禁)"),
@ApiModelProperty("非法的token")
ILLGER_TOKEN(-103, "非法的token"),
@ApiModelProperty("未提供token或token超时")
TOKEN_EXPIRED(-104, "未提供token或token超时"),
@ApiModelProperty("验证码不正确")
AUTH_CODE_ERROR(-105, "验证码不正确"),
@ApiModelProperty("验证码未找到")
AUTH_CODE_NOT_FOUND(-106, "验证码未找到"),
@ApiModelProperty("验证码过期")
AUTH_CODE_PAST_DUE(-107, "验证码过期"),
@ApiModelProperty("验证码渲染失败")
AUTH_CODE_RENDER_FAIL(-108, "验证码渲染失败"),
@ApiModelProperty("权限认证角色异常")
ROLE_ERROR(-200, "权限认证角色异常"),
@ApiModelProperty("权限认证权限异常")
PERMISSION_ERROR(-201, "权限认证权限异常"),
@ApiModelProperty("请求方式错误")
REQUEST_METHOD_ERROR(-300, "请求方式错误"),
@ApiModelProperty("参数错误")
PARAM_ERROR(-301, "参数错误"),
@ApiModelProperty("校验错误")
VALIDATION_ERROR(-302, "校验错误"),
@ApiModelProperty("业务错误")
BUSINESS_ERROR(-303, "业务错误"),
@ApiModelProperty("接口限流了")
INTERFACE_CURRENT_LIMITING(-401, "接口限流了"),
@ApiModelProperty("服务降级了")
SERVICE_DEGRADED(-402, "服务降级了"),
@ApiModelProperty("热点参数限流了")
HOT_PARAM_CURRENT_LIMITING(-403, "热点参数限流了"),
@ApiModelProperty("触发系统保护规则")
TRIGGER_SYSTEM_PROTECTION_RULE(-404, "触发系统保护规则"),
@ApiModelProperty("授权规则不通过")
AUTHORIZATION_RULE_FAILS(-405, "授权规则不通过"),
@ApiModelProperty("该地址不存在")
NOT_FOUND_ERROR(404, "该地址不存在"),
@ApiModelProperty("系统繁忙,请稍后再试")
SYSTEM_ERROR(500, "系统繁忙,请稍后再试");
@ApiModelProperty("异常错误编号")
private final Integer code;
@ApiModelProperty("异常错误描述")
private final String msg;
private ErrorEnums(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return this.code;
}
public String getMsg() {
return this.msg;
}
}
异常类
package 包名路径.exception;
import cn.tedu.enums.ErrorEnums;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
* 业务异常类
* @author 孙永潮
* @date 2022/12/21
*/
@NoArgsConstructor
public class BusinessException extends RuntimeException{
private static final long serialVersionUID = 3034121940056795549L;
@Getter
private Integer code;
public BusinessException(String msg) {
super(msg);
// this.code = ErrorEnums.SYSTEM_ERROR.getCode();
}
public BusinessException(ErrorEnums errorEnums) {
super(errorEnums.getMsg());
this.code = errorEnums.getCode();
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
测试类
import 路径.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
@Slf4j
class DemoApplicationTests {
@Test
void contextLoads() {
throw new BusinessException("抛个异常看看");
}
}
梦中小路 我不会停下脚步
都想成功 可成功毕竟占少数
我慢慢 从横冲 直撞 到 变牢固
我在肮脏的泥泞里面找宝物
没经历苦难 怎么叫做生活
每一次分叉 口 我都仔细斟酌
现在我站在这里
太阳它照常升起
不管遇到什么笑着面对才是真理
——选自VAVA毛衍七《Life’s a struggle》歌词