在 java 自定义异常中构建 builder 模式,核心做法是创建一个静态内部类 builder,将异常的字段(如错误码、消息)设为该类的成员变量并提供链式设置方法,最后通过 build() 方法实例化异常对象。这样做的好处是将复杂的异常初始化逻辑封装在 builder 中,调用方可以按需设置参数,保持代码整洁且支持不可变异常对象。

如何设计 Builder 类的结构以支持链式调用
设计 Builder 类时,需要为每个需要设置的属性提供对应的 setter 方法,这些方法返回 Builder 自身实例,从而实现链式调用。同时,Builder 类必须持有对目标异常类的引用或能够创建其实例。通常,Builder 会包含一个无参构造函数用于初始化默认值,以及一个 build() 方法用于最终生成异常对象。在 build() 方法中,可以进行必要的校验,例如检查必填字段是否为空,若校验失败则抛出 IllegalStateException。这种结构确保了异常对象的不可变性,因为一旦通过 build() 创建,其状态便不再改变。

public class BusinessException extends Exception {
private final String errorCode;
private final String message;
private BusinessException(Builder builder) {
super(builder.message);
this.errorCode = builder.errorCode;
this.message = builder.message;
}
public static class Builder {
private String errorCode;
private String message;
public Builder() {
// 默认值
}
public Builder errorCode(String code) {
this.errorCode = code;
return this;
}
public Builder message(String msg) {
this.message = msg;
return this;
}
public BusinessException build() {
if (errorCode == null || message == null) {
throw new IllegalStateException("errorCode and message are required");
}
return new BusinessException(this);
}
}
public String getErrorCode() {
return errorCode;
}
}
如何在业务代码中使用 Builder 构建异常
在业务代码中,使用 Builder 构建异常非常直观。只需调用 BusinessException.Builder 的静态内部类,依次调用 errorCode() 和 message() 方法,最后调用 build() 即可得到异常实例。这种方式比传统的构造函数更灵活,特别是当异常有很多可选参数时。开发者可以直接在 throw 语句中嵌入 Builder 调用,使代码更加紧凑。例如,throw new BusinessException.Builder().errorCode("E001").message("User not found").build();。这种用法不仅提高了代码的可读性,还减少了样板代码的数量。
在代码库出现结构漂移之前,扫描JS或TS代码库中的禁止导入、循环依赖、孤立模块和其他依赖规则违规情况。

// 使用示例
public void findUser(String userId) {
if (userId == null) {
throw new BusinessException.Builder()
.errorCode("E001")
.message("User ID cannot be null")
.build();
}
// 其他逻辑
}
Builder 模式中如何处理必填字段的校验
在 Builder 模式中,处理必填字段的校验通常在 build() 方法中进行。在 build() 方法中,检查所有必填字段是否已设置,如果有任何必填字段为空或未设置,则抛出 IllegalStateException。这样可以确保在异常对象被创建之前,所有必要的信息都已就绪。例如,在上述代码中,build() 方法检查了 errorCode 和 message 是否为空,如果为空则抛出异常。这种校验机制保证了异常对象的一致性和完整性,避免了因缺少关键信息而导致的运行时错误。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










