SpringBoot学习记录3——包装器业务异常类、跨域

一、包装器业务异常类
包装器我的理解是,类似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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值