使用 completablefuture 的 whencomplete 方法可以在任务完成时(无论成功或异常)执行日志记录逻辑。具体做法是在构建异步任务后,链式调用 .whencomplete((result, throwable) -> ...),在 lambda 表达式中判断 throwable 是否为空来决定打印成功还是失败日志,该方法返回原 completablefuture 实例,不会中断后续流程。

如何区分成功与异常状态进行日志输出
在 whenComplete 的回调中,通过检查第二个参数 Throwable 即可区分状态。如果 throwable 为 null,说明任务正常结束,此时第一个参数 result 包含计算结果;如果 throwable 不为 null,说明任务抛出异常,此时 result 为 null。开发者应在此处分别调用不同的日志级别函数,例如成功时记录 INFO,失败时记录 ERROR 并打印堆栈。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class LogExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// 模拟业务逻辑
return "Success";
}).whenComplete((result, ex) -> {
if (ex == null) {
System.out.println("[INFO] Task completed with result: " + result);
} else {
System.out.println("[ERROR] Task failed: " + ex.getMessage());
}
});
// 获取最终结果以阻塞主线程等待完成
String finalResult = future.get();
System.out.println("Main thread got: " + finalResult);
}
}whenComplete 是否会吞掉异常影响后续处理
whenComplete 不会吞掉异常,它仅用于消费结果和副作用(如日志),并将异常继续传递给后续的依赖任务。如果在 whenComplete 内部没有捕获异常,或者后续步骤需要处理异常,异常会沿着链式调用继续传播。这与 exceptionally 不同,后者专门用于恢复或转换异常结果。因此,在 whenComplete 中记录日志是安全的,不会影响 thenApply 或 get() 对异常的处理能力。
立即学习“Java免费学习笔记(深入)”;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class ExceptionPropagation {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("Simulated Error");
}).whenComplete((result, ex) -> {
// 记录日志,但不处理异常
if (ex != null) {
System.err.println("[LOG] Caught exception: " + ex.getMessage());
}
}).thenApply(res -> {
// 由于上面抛出了异常,这里不会执行
return res.toUpperCase();
}).exceptionally(ex -> {
// 这里捕获了异常并返回默认值
return "Fallback Value";
});
System.out.println(future.get());
}
}基于 supplyAsync 输入结果的日志记录验证
当输入为正常字符串时,whenComplete 接收到的 result 为该字符串,throwable 为 null。上述代码运行后,控制台首先输出 [LOG] 或 [INFO] 相关的成功日志,随后主线程通过 future.get() 获取到原始返回值。这验证了在无异常路径下,日志记录器能准确获取业务数据,且不影响数据的透传。


















