定义通过错误接口类:CommonError
public interface CommonError {
// 获取错误码
int getErrorCode();
// 获取错误消息
String getErrorMsg();
// 设置错误消息,用于覆盖Enumeration中设置的默认错误消息
CommonError setErrorMsg(String errorMsg);
}
定义错误枚举类:EnumError
/**
* 继承至CommonError
*/
public enum EnumError implements CommonError {
// 10000开头为通用错误类型
UNKNOWN_ERROR(10001, "未知错误"),
PARAMETER_VALIDATION_ERROR(10002, "参数不合法"),
// 20000开头为用户信息相关错误码定义
USER_NOT_EXIST(20001, "用户不存在"),
USER_LOGIN_FAIL(20003, "用户名或密码错误"),
USER_NOT_LOGIN(20004, "用户未登录"),
// 30000开头为商品相关错误码定义
STOCK_NOT_ENOUGH(30001, "库存不足"),
;
// 定义错误码和错误消息字段
private int errorCode;
private String errorMsg;
EnumError(int errorCode, String errorMsg) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
@Override
public int getErrorCode() {
return errorCode;
}
@Override
public String getErrorMsg() {
return errorMsg;
}
// 主要的作用:可以修改错误码对应的errorMessage
@Override
public CommonError setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
return this;
}
}
定义业务异常类:BusinessException
/**
* 包装器业务异常类实现模式
*/
public class BusinessException extends Exception implements CommonError {
private CommonError commonError;
// 通用构造器
public BusinessException(CommonError commonError){
super();
this.commonError = commonError;
}
// 覆盖ErrorMessage的构造器
public BusinessException(CommonError commonError, String errorMsg){
super();
this.commonError = commonError;
this.commonError.setErrorMsg(errorMsg);
}
@Override
public int getErrorCode() {
return this.commonError.getErrorCode();
}
@Override
public String getErrorMsg() {
return this.commonError.getErrorMsg();
}
// 覆盖默认的errorMessage
@Override
public CommonError setErrorMsg(String errorMsg) {
this.commonError.setErrorMsg(errorMsg);
return this;
}
}