Unified Error Recovery Patterns
You'll learn how to implement fallback logic that handles both success and failure cases uniformly using handle.
The Core Idea
While exceptionally only kicks in when something goes wrong, handle gives you a single place to process both successful results and exceptions. This creates a unified error recovery pattern where you can inspect the outcome, decide what to do, and return a consistent result regardless of whether the pipeline succeeded or failed.
Think of it like a security checkpoint at an airport: every passenger goes through the same gate, but the staff can handle both valid travelers (success) and those with issues (exceptions) in one unified process, rather than having separate lines.
When to Use Unified Recovery
Use handle when you need to:
- Apply the same transformation logic to both success and failure paths
- Make decisions based on whether an error occurred
- Normalize different outcomes into a single format
- Clean up resources regardless of success or failure
Practical Pattern
CompletableFuture<String> result = CompletableFuture
.supplyAsync(() -> fetchUserData(userId))
.handle((data, ex) -> {
if (ex != null) {
// Failure path: return fallback
return "Guest User";
} else {
// Success path: transform or validate
return data != null ? data : "Anonymous";
}
});
Both branches return the same type, creating a unified result. You could also add logging, metrics collection, or resource cleanup that applies to both paths.
Single Point of Control
The beauty of this pattern is that all outcomes flow through one function. You're not scattering error handling across multiple exceptionally calls—you have one place where success and failure converge.
Key Takeaway: Use handle to create unified error recovery patterns where both successful results and exceptions are processed in a single function, enabling consistent fallback logic and simplified control flow.