异常处理是对Exception的统一管理,当程序出现问题会将出错信息打印出来,但是很多时候我们得到的是很多的堆栈信息和部分可以直接进行判断的信息,通过自定义的封装可以对异常信息进行统一管理,返回我们可以判断的异常信息。
定义CommonError接口
package com.miaoshaproject.error;/*
public interface CommonError {
public int getErrCode();
public String getErrMsg();
public CommonError setErrMsg(String errMsg);
}
定义枚举类EmBusinessError
package com.miaoshaproject.error;/*
public enum EmBusinessError implements CommonError{
USER_NOT_EXIST(10001,"用户不存在"),
UNKNOWN_ERROR(10002,"未知错误"),
PARAMETER_VALIDATION_ERROR(20001,"参数不合法"),
USER_LOGIN_FAIL(20002,"用户手机号或密码不正确"),
USER_NOT_LOGIN(20003,"用户还未登陆"),
//30000开头为交易信息错误定义
STOCK_NOT_ENOUGH(30001,"库存不足"),
;
private EmBusinessError(int errCode, String errMsg) {
this.errCode = errCode;
this.errMsg = errMsg;
}
private int errCode;
private String errMsg;
@Override
public int getErrCode() {
return this.errCode;
}
@Override
public String getErrMsg() {
return this.errMsg;
}
@Override
public CommonError setErrMsg(String errMsg) {
this.errMsg=errMsg;
return this;
}
}
定义异常处理类BusinessException
package com.miaoshaproject.error;/*
public class BusinessException extends Exception implements CommonError{
private CommonError commonError;
public BusinessException(CommonError commonError) {
super();
this.commonError = commonError;
}
public BusinessException(CommonError commonError,String errMsg){
super();
this.commonError = commonError;
this.commonError.setErrMsg(errMsg);
}
public CommonError getCommonError(){
return commonError;
}
@Override
public int getErrCode() {
return this.commonError.getErrCode();
}
@Override
public String getErrMsg() {
return this.commonError.getErrMsg();
}
@Override
public CommonError setErrMsg(String errMsg) {
this.commonError.setErrMsg(errMsg);
return this;
}
}
使用
返回具体结果:
if (result.isHasErrors() ) {
throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,result.getErrMsg());
}
自定义返回值:
throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "手机号已重复注册");