Type Transformation in handle
You'll learn how handle can convert your CompletableFuture to a different result type, even when errors occur.
The Core Idea
While handle lets you process both success and failure cases, it also gives you the unique ability to change the result type entirely. You can take a CompletableFuture<String>, for example, and transform it into a CompletableFuture<Integer>, CompletableFuture<Optional<String>>, or any other type—regardless of whether the original computation succeeded or failed.
This is powerful for error recovery patterns where you want to normalize different outcomes into a consistent type that downstream code can work with predictably.
How It Works
The handle method's BiFunction takes the result and exception, but its return type determines the new type of the CompletableFuture. You're not restricted to returning the original type.
CompletableFuture<String> future = supplyAsync(() -> {
throw new RuntimeException("Failed to fetch name");
});
CompletableFuture<Integer> lengthFuture = future.handle((result, ex) -> {
if (ex != null) {
return 0; // Default length for errors
}
return result.length(); // Transform String to Integer
});
System.out.println(lengthFuture.join()); // 0
Here, a CompletableFuture<String> becomes a CompletableFuture<Integer>. Whether the original future succeeded with a string or failed with an exception, we always return an integer.
Common Transformation Patterns
Wrapping in Optional:
CompletableFuture<Optional<String>> optFuture = future.handle((result, ex) ->
ex != null ? Optional.empty() : Optional.of(result)
);
Converting to status objects:
CompletableFuture<Result> statusFuture = future.handle((result, ex) ->
ex != null ? Result.failure(ex.getMessage()) : Result.success(result)
);
Key Takeaway: handle not only processes both success and failure but also transforms your CompletableFuture into a completely different type, enabling elegant type conversions and unified error recovery patterns.