有了上篇统一异常处理,接下去就要做统一错误码了,我们在与第三方平台对接时,经常会看到对接文档中有错误码一览,这样你在对接过程中可以快速定位问题,在我们的项目中该怎么实现呢。
第一步,定义错误码接口
public interface BaseErrorCode {
//错误码
int getValue();
//错误描述
String getDesc();
}
第二步,在自定义异常类ServiceFailException中接收该接口并处理
public ServiceFailException(BaseErrorCode errorCode) {
this(errorCode, false);
}
public ServiceFailException(BaseErrorCode errorCode, boolean print) {
this(errorCode.getDesc(), errorCode.getValue(), print);
}
第三步,定义错误码枚举类,所有错误码写在这里面
public enum ErrorCode implements BaseErrorCode {
PAY_ERROR(50001, "支付错误");
private int value;
private String desc;
// 构造方法
ErrorCode(int value, String desc) {
this.value = value;
this.desc = desc;
}
@Override
public int getValue() {
return this.value;
}
@Override
public String getDesc() {
return this.desc;
}
}
演示
public void pay(int money) {
if (money != 100) {
throw new ServiceFailException(ErrorCode.PAY_ERROR);
}
}

参考项目(模块: SpringBoot-HelloWorld): https://gitee.com/huatin/java-test
博客介绍了在项目中实现统一错误码的方法。在与第三方平台对接时,错误码有助于快速定位问题。实现步骤包括定义错误码接口、在自定义异常类中接收并处理该接口、定义错误码枚举类。还给出了参考项目链接。
3302

被折叠的 条评论
为什么被折叠?



