使用异常构建器设置属性,核心做法是定义一个静态内部类继承 throwable 并实现 throwable$throwableconstructor 接口,通过反射调用私有构造函数来实例化异常对象。这样可以在抛出异常前动态填充自定义字段,如错误码或用户 id,而无需为每个组合编写多个构造函数。

如何设计支持构建器的异常类结构
要实现这一机制,需要创建一个具体的异常类,其中包含一个私有的全参构造函数和一个公开的静态工厂方法。该工厂方法负责接收所有需要的属性参数,并将它们传递给构建器逻辑。这种结构确保了异常对象的不可变性,同时提供了清晰的 API 供调用者使用。

public class CustomException extends Exception {
private final String errorCode;
private final String userId;
// 私有构造函数,由构建器通过反射调用
private CustomException(String message, Throwable cause,
String errorCode, String userId) {
super(message, cause);
this.errorCode = errorCode;
this.userId = userId;
}
// 静态工厂方法,作为构建入口
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String message;
private Throwable cause;
private String errorCode;
private String userId;
public Builder message(String msg) { this.message = msg; return this; }
public Builder cause(Throwable thr) { this.cause = thr; return this; }
public Builder errorCode(String code) { this.errorCode = code; return this; }
public Builder userId(String id) { this.userId = id; return this; }
public CustomException build() throws RuntimeException {
try {
// 获取私有构造函数
Constructor<customexception> ctor = CustomException.class.getDeclaredConstructor(
String.class, Throwable.class, String.class, String.class
);
ctor.setAccessible(true);
// 通过反射实例化
return ctor.newInstance(message, cause, errorCode, userId);
} catch (Exception e) {
throw new RuntimeException("Failed to build exception", e);
}
}
}
public String getErrorCode() { return errorCode; }
public String getUserId() { return userId; }
}</customexception>
上述代码展示了完整的实现。首先定义了 CustomException 类,包含 errorCode 和 userId 两个自定义字段。私有构造函数接受这些字段以及标准的 message 和 cause。静态内部类 Builder 提供了链式调用的方法,允许调用者逐步设置属性。在 build() 方法中,使用 getDeclaredConstructor 获取私有构造函数,并通过 setAccessible(true) 绕过访问限制,最后调用 newInstance 创建异常实例。这种方式避免了为每种属性组合编写构造函数的繁琐工作。
如何在业务逻辑中调用构建器并抛出异常
在实际业务代码中,可以通过调用 CustomException.builder() 开始构建过程,依次设置所需的属性,最后调用 build() 获取异常实例并抛出。这种方法使得异常信息的组装更加灵活和可读,特别是在需要传递多个上下文信息时。

public class UserService {
public void processUser(String userId) {
if (userId == null || userId.isEmpty()) {
try {
throw CustomException.builder()
.message("Invalid user ID")
.errorCode("ERR_USER_001")
.userId(userId)
.build();
} catch (CustomException e) {
// 处理异常,例如记录日志
System.out.println("Caught: " + e.getMessage());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("User ID: " + e.getUserId());
}
}
}
public static void main(String[] args) {
UserService service = new UserService();
service.processUser(null);
}
}
这段代码演示了如何在 UserService 中使用构建器。当 userId 为空时,调用 CustomException.builder() 创建构建器实例,然后链式调用 message()、errorCode() 和 userId() 设置属性。最后调用 build() 抛出异常。在 main 方法中,捕获该异常并打印其消息、错误码和用户 ID,验证了属性的正确设置。这种模式不仅简化了异常的创建,还提高了代码的可维护性和可读性。
基于 errorCode 属性在异常处理中的具体应用
当异常被抛出后,可以通过调用 getErrorCode() 方法获取设置的错误码,从而在 catch 块中进行针对性的处理。例如,根据错误码决定是重试操作、返回特定的 HTTP 状态码还是记录不同的日志级别。这种基于属性的处理方式使得异常处理更加细粒化和自动化。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











