在 completablefuture 中使用函数式接口处理异常,核心是调用 exceptionally 方法并传入一个实现 java.util.function.function 接口的 lambda 表达式。该接口接收一个 throwable 类型的参数(即捕获到的异常),并返回与原始 completablefuture 相同的泛型类型 t。通过这种方式,你可以在不中断流式调用的前提下,为异常提供默认值、重试逻辑或降级数据。

如何编写 Function 接口来处理异常并返回默认值?
要实现这个功能,你需要创建一个 Function 实例,其中输入 T 是 java.lang.Throwable,输出 U 是你希望恢复的数据类型。例如,如果原始任务是获取用户信息(返回 User 对象),当发生异常时,你可以返回一个空的 User 对象或者抛出新的运行时异常。关键在于确保返回值类型与 thenApply 等后续操作期望的类型一致。

import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
public class ExceptionalExample {
public static void main(String[] args) {
// 模拟一个可能失败的异步任务
CompletableFuture<string> future = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("Simulated Error");
});
// 使用 exceptionally 处理异常
CompletableFuture<string> recoveredFuture = future.exceptionally(new Function<throwable string>() {
@Override
public String apply(Throwable t) {
System.out.println("Caught exception: " + t.getMessage());
return "Default Value"; // 返回默认值
}
});
// 获取结果
try {
String result = recoveredFuture.get();
System.out.println("Result: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}</throwable></string></string>
运行上述代码将输出:
Caught exception: Simulated Error
Result: Default Value
如何在 exceptionally 中实现重试机制?
除了返回默认值,你还可以在 exceptionally 中实现简单的重试逻辑。这通常涉及再次提交一个新的 CompletableFuture 任务。需要注意的是,exceptionally 本身不会自动重试,你需要手动创建一个新的 Future 并在其内部执行重试逻辑,或者递归地调用自身(需谨慎避免无限循环)。更常见的做法是使用 handle 或结合 retry 库,但在纯函数式接口场景下,我们可以构造一个新的 Future 来替代失败的那个。
使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。

import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
public class RetryExample {
private static int retryCount = 0;
public static void main(String[] args) {
CompletableFuture<string> future = createTaskWithRetry();
try {
String result = future.get();
System.out.println("Final Result: " + result);
} catch (Exception e) {
System.out.println("Failed after retries: " + e.getMessage());
}
}
private static CompletableFuture<string> createTaskWithRetry() {
return CompletableFuture.supplyAsync(() -> {
if (retryCount () {
@Override
public String apply(Throwable t) {
if (retryCount <p>由于 <code>exceptionally</code> 的设计限制,它更适合用于“故障转移”而非“重试”。如果需要复杂的重试,建议使用 <code>handle</code> 方法配合循环,或使用如 Resilience4j 等库。上述代码展示了如何在异常回调中进行状态判断和分支处理。</p>
<h2>exceptionally 返回 null 会对后续 thenApply 产生什么影响?</h2>
<p>如果在 <code>exceptionally</code> 的 <code>apply</code> 方法中返回了 <code>null</code>,后续的 <code>thenApply</code> 或 <code>thenAccept</code> 仍然会被执行,但传入它们的参数将是 <code>null</code>。这意味着链式调用不会中断,而是继续以 <code>null</code> 作为输入进行下一步计算。开发者必须确保后续操作能够安全地处理 <code>null</code> 值,否则可能会引发 <code>NullPointerException</code>。这与 <code>completeExceptionally</code> 导致整个链断裂的行为截然不同。</p></string></string>
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










