易于扩展的Spring异常处理

  • 首先定义一个基础的异常接口
/**
 * 基础异常接口
 *
 * @author moguchen
 */
public interface BaseExceptionInterface {

    /**
     * 获取response的code
     *
     * @return code
     */
    Integer getCode();

    /**
     * 获取response的message
     *
     * @return message
     */
    String getMessage();

}
  • 然后基于此接口扩展不同的业务异常枚举类,这里给一个万能的用户异常枚举类demo
/**
 * @author moguchen
 */
public enum UserExceptionEnum implements BaseExceptionInterface {
    /**
     * 用户相关异常
     */
    USER_NOT_EXIST_ERROR(10000, "用户不存在"),
    ;


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

    /**
     * 错误描述
     */
    private final String message;

    UserExceptionEnum(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    @Override
    public Integer getCode() {
        return code;
    }

    @Override
    public String getMessage() {
        return message;
    }
}
  • 然后定义业务异常类,构建方法根据实际情况采用

/**
 * 通用异常类
 * 扩展异常只需要扩展对应的异常枚举类
 *  * @author moguchen
 */
public class CommonException extends RuntimeException {

    /**
     * 异常码
     */
    private final Integer errorCode;

    /**
     * 异常信息
     */
    private final String errorMessage;

    public CommonException(Integer errorCode, String errorMessage) {
        super();
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    public CommonException(BaseExceptionInterface baseExceptionInterface) {
        super(baseExceptionInterface.getMessage());
        this.errorCode = baseExceptionInterface.getCode();
        this.errorMessage = baseExceptionInterface.getMessage();
    }

    public CommonException(BaseExceptionInterface baseExceptionInterface, Object... params) {
        this(baseExceptionInterface.getCode(), MessageFormat.format(baseExceptionInterface.getMessage(), params));
    }

    public CommonException(BaseExceptionInterface baseExceptionInterface, Throwable throwable) {
        super(baseExceptionInterface.getMessage(), throwable);
        this.errorCode = baseExceptionInterface.getCode();
        this.errorMessage = baseExceptionInterface.getMessage();
    }

    public Integer getErrorCode() {
        return errorCode;
    }

    public String getErrorMessage() {
        return errorMessage;
    }
}
  • 使用的时候只需要new即可
throw new CommonException(UserExceptionEnum.USER_NOT_EXIST_ERROR);
  • 扩展业务异常时也只需要扩展对应的异常枚举类信息即可
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值