Exception Handling

Learn patterns and best practices for handling exceptions in your API gateway. Build resilient systems that recover gracefully from failures.

Circuit Breaker

Stop making requests after repeated failures. Allow services time to recover before retrying.

↩️ Fallback

Provide alternative responses when primary service fails. Maintain user experience.

🔄 Retry

Automatically retry failed requests with exponential backoff. Handle transient failures.

Implementation Patterns

// Exception handling middleware async exceptionHandler(ctx, next) { try { await next(); } catch (error) { // Log the error logger.error(error.message); // Check circuit breaker if (circuitBreaker.isOpen()) { // Return fallback return ctx.json(fallbackResponse); } // Determine retry strategy if (isRetryable(error)) { await retryWithBackoff(ctx); } // Return error response ctx.status = error.statusCode || 500; ctx.body = { error: error.message }; } }

Key Patterns

Circuit Breaker Pattern

Track failures and open circuit after threshold. After timeout, allow limited requests to test recovery. failureThreshold: 5, timeout: 30s

Fallback Pattern

Provide cached responses or default values when service fails. Users get acceptable response instead of error.

Bulkhead Pattern

Isolate failures to specific resources. Prevent cascade failures from affecting entire system.

Timeout Pattern

Set reasonable timeouts for all operations. Prevent hanging requests from consuming resources.

99.9%
Uptime
60%
Faster Recovery
80%
Fewer Errors

Common Questions

When should I use circuit breaker?
Use circuit breaker when calling external services that may become unavailable. It prevents cascade failures and allows services to recover.
What's the best fallback strategy?
Depends on your use case. Common strategies: cached responses, default values, degraded functionality, or graceful error messages.
How many retries are appropriate?
3-5 retries with exponential backoff typically works well. Too many retries can overload recovering services.

Related Resources

Error Codes

Reference

Retry Strategies

Patterns

Prompt Caching

Optimization

Home

Back to hub