Course contentsShow
← Java
Lesson 2840 of 2,87051. CompletableFutureFree lesson

Logging Exceptions Before Returning Fallbacks

Best practice of logging exception details within exceptionally before providing a recovery value.

Logging Exceptions Before Returning Fallbacks

What you'll learn: How to record exception details in exceptionally before providing a recovery value, ensuring you don't silently swallow important error information.

The Problem: Silent Failures

When you use exceptionally to return fallback values, you create a safety net—but you also risk hiding critical error information. If you simply return a default value without recording what went wrong, you'll have no visibility into failures happening in production.

Best Practice: Log Then Recover

Always log exception details within your exceptionally handler before returning your fallback:

CompletableFuture<String> future = fetchUserDataAsync(userId)
    .exceptionally(ex -> {
        // Log the full exception details
        System.err.println("Failed to fetch user data: " + ex.getMessage());
        ex.printStackTrace();
        
        // Then return fallback
        return "Guest User";
    });

Think of It Like a Safety Net with Cameras

Imagine a trapeze artist with a safety net below. If they fall, the net catches them (the fallback), but you also want cameras recording why they fell—was it wind? Equipment failure? Without logging, you catch the fall but learn nothing about preventing future issues.

Real-World Pattern

CompletableFuture<Integer> result = calculateRiskScore(account)
    .exceptionally(ex -> {
        // Production-quality logging
        logger.error("Risk calculation failed for account {}: {}", 
                     account.getId(), ex.getMessage(), ex);
        
        // Return conservative fallback
        return 100; // Maximum risk score as safety measure
    });

This approach gives you observability—you can monitor error rates, investigate root causes, and improve system reliability while still maintaining graceful degradation for users.

Key Takeaway: Always log exception details in exceptionally handlers before returning fallbacks; silent recovery is invisible failure that prevents debugging and system improvement.