Processing Successful Results with handle
What you'll learn: How to use handle to transform successful results in a CompletableFuture pipeline, even when no exception has occurred.
The Dual Nature of handle
While handle is powerful for error recovery, it's equally useful for processing successful results. Unlike exceptionally, which only activates on failure, handle always executes whether the future completes normally or exceptionally. This makes it perfect when you need to examine the result and potentially transform it regardless of outcome.
Transforming Success Cases
When a CompletableFuture completes successfully, handle receives the actual result as its first parameter and null as the second (Throwable) parameter. You can check if the exception is null to confirm success, then transform the value:
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 42);
CompletableFuture<String> result = future.handle((value, ex) -> {
if (ex == null) {
// Success path: transform the value
return "Success: " + value;
} else {
// Error path: provide fallback
return "Failed: " + ex.getMessage();
}
});
System.out.println(result.join()); // Output: "Success: 42"
Think of It as a Universal Processor
Imagine handle as a quality control station on an assembly line. Every item passes through, whether perfect or defective. You inspect each one and decide what to output—polishing successful items or marking defective ones for disposal.
Why Use handle for Success?
Sometimes you need uniform processing logic that applies to both outcomes. For example, logging, formatting, or wrapping results in a common container type works naturally with handle since you write one function instead of separate success and error handlers.
Key Takeaway: handle processes both successful and failed CompletableFutures, making it ideal when you need to transform results regardless of outcome—check if the exception parameter is null to identify success cases.