一、包装器业务异常类
包装器我的理解是,类似int、long、float等,当我们要把它当做一个类来处理时,我们采用Integer、Long、Float类来包装他们。
在开发过程中,我们可以用包装器的模式来开发相关异常。
如:首先定义一个异常接口CommonError:
public interface CommonError {
public int getErrCode();
public String getErrMsg();
public CommonError setErrMsg(String errMsg);
}
再定义实现该接口的枚举类EmBusinessError,该类可以用来定义各种异常:
public enum EmBusinessError implements CommonError {
//通用错误类型10001
PARAMETER_VALIDATION_ERROR(10001,"参数不合法"),
UNKNOW_ERROR(10002,"未知错误"),
//20000开头为用户信息相关错误定义
USER_NOT_EXIST(20001,"用户不存在")
;
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:
public class BusinessException extends Exception implements CommonError {
private CommonError commonError;
//直接接受EmBUsinessError的传参用于构造异常
public BusinessException(CommonError commonError){
super();
this.commonError = commonError;
}
//接受自定义errMsg的方式构造业务异常
public BusinessException(CommonError commonError,String errMsg){
super();
this.commonError = commonError;
this.commonError.setErrMsg(errMsg);
}
@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;
}
}
最后用该方法试抛出异常:
throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
二、跨域相关的问题
①若无cookie
前台
xhrFields:{withCredentials:false},
后台
@CrossOrigin
②若有cookie
前台
xhrFields:{withCredentials:true}
后台
@CrossOrigin(origins = {"*"}, allowCredentials = "true")
参考:https://segmentfault.com/a/1190000011145364