实现说明
整个示例围绕类 ProfileService和函数 loadProfile、main组织。
守卫条件成立时抛出 IllegalStateException,而不是返回一个假值。
使用要点
- 直接运行文件,输出会带上标签,比如
observed error:、observed value:、main continues with:——输出的每一行都能指回产生它的那次调用。 - 运行整个文件:
main会依次驱动loadProfile。
常见问题
坏输入有失败路径吗?
代码会拒绝继续:抛出 IllegalStateException,此时状态仍可恢复。
运行「CompletableFuture 的异常恢复与观察」会打印什么?
整个文件跑完,输出行以 observed error:、observed value:、main continues with: 这类前缀开头。
入口签名:static String loadProfile(String id)
核心语句
throw new IllegalStateException("profile not found: " + id);
return "profile-" + id;
String fallback = CompletableFuture
.supplyAsync(() -> loadProfile("ghost"))
.exceptionally(error -> "profile-guest")
.join();
代码示例
import java.util.concurrent.CompletableFuture;
public class ProfileService {
static String loadProfile(String id) {
if (id.equals("ghost")) {
throw new IllegalStateException("profile not found: " + id);
}
return "profile-" + id;
}
public static void main(String[] args) {
// whenComplete:只旁观结果/异常,不替换任何值;join 保证回调先执行完
String observed = CompletableFuture
.supplyAsync(() -> loadProfile("42"))
.whenComplete((profile, error) -> {
if (error != null) {
System.out.println("observed error: " + error.getMessage());
} else {
System.out.println("observed value: " + profile);
}
})
.join();
System.out.println("main continues with: " + observed);
// 失败恢复 recovery:exceptionally 把异常换成兜底值,链继续向下走
String fallback = CompletableFuture
.supplyAsync(() -> loadProfile("ghost"))
.exceptionally(error -> "profile-guest")
.join();
System.out.println("recovered value: " + fallback);
// handle:成功与异常共用同一出口,二选一变换
String rendered = CompletableFuture
.supplyAsync(() -> loadProfile("ghost"))
.handle((profile, error) -> profile != null
? profile.toUpperCase()
: "anonymous (" + error.getMessage() + ")")
.join();
System.out.println("handled value: " + rendered);
}
}