handle with Logging and Side Effects
What you'll learn: How to implement logging and monitoring within handle while keeping your results flowing cleanly to downstream operations.
The Core Idea
When you use handle, you're intercepting both successes and failures in your async pipeline. This creates the perfect opportunity to log what happened, collect metrics, or trigger monitoring alerts—all without disrupting the data flowing to the next stage.
Think of it like a security checkpoint at an airport: inspectors check your luggage (log the state), possibly stamp documents (side effects), but ultimately let you and your bags continue to your gate (preserve the result).
How It Works in Practice
The key is that handle receives both the result and the exception, allowing you to observe what happened. You perform your logging or side effects, then decide what value to return downstream:
CompletableFuture<Integer> future = CompletableFuture
.supplyAsync(() -> {
if (Math.random() > 0.5) throw new RuntimeException("Random failure");
return 42;
})
.handle((result, ex) -> {
if (ex != null) {
System.err.println("Error occurred: " + ex.getMessage());
// Log to monitoring system, increment error counter, etc.
return -1; // Return fallback value
} else {
System.out.println("Success with result: " + result);
// Log to audit trail, record latency, etc.
return result; // Pass through the original result
}
})
.thenApply(value -> value * 2); // Downstream operations continue normally
Notice how the logging happens inside handle, but the result (whether original or fallback) flows cleanly to thenApply.
Key Takeaway: Use handle for logging and side effects by observing both success and failure paths, performing your monitoring actions, then returning an appropriate value to keep the pipeline flowing—all in one unified location.