Error Recovery in JavaScript
Recover from errors gracefully
AdvancedError HandlingExample 9 of 10
error-recovery.js
1// Method 1: Fallback values2function fetchWithFallback(url, fallback) {3 return fetch(url)4 .then(response => response.json())5 .catch(error => {6 console.warn('Fetch failed, using fallback:', error);7 return fallback;8 });9}1011// Method 2: Retry with fallback12async function operationWithFallback(primary, fallback, maxRetries = 3) {13 for (let i = 0; i < maxRetries; i++) {14 try {15 return await primary();16 } catch (error) {17 if (i === maxRetries - 1) {18 console.warn('Primary failed, using fallback');19 return await fallback();20 }21 await new Promise(resolve => setTimeout(resolve, 1000));22 }23 }24}2526// Method 3: Circuit breaker27class CircuitBreaker {28 constructor(threshold = 5, timeout = 60000) {29 this.failures = 0;30 this.threshold = threshold;31 this.timeout = timeout;32 this.state = 'CLOSED'; // CLOSED, OPEN, HALF_OPEN33 this.nextAttempt = Date.now();34 }3536 async execute(fn) {37 if (this.state === 'OPEN') {38 if (Date.now() < this.nextAttempt) {39 throw new Error('Circuit breaker is OPEN');40 }41 this.state = 'HALF_OPEN';42 }4344 try {45 const result = await fn();46 this.onSuccess();47 return result;48 } catch (error) {49 this.onFailure();50 throw error;51 }52 }5354 onSuccess() {55 this.failures = 0;56 this.state = 'CLOSED';57 }5859 onFailure() {60 this.failures++;61 if (this.failures >= this.threshold) {62 this.state = 'OPEN';63 this.nextAttempt = Date.now() + this.timeout;64 }65 }66}6768const breaker = new CircuitBreaker();69breaker.execute(() => fetch('https://api.example.com/data'));7071// Method 4: Graceful degradation72function featureWithFallback(feature, fallback) {73 try {74 return feature();75 } catch (error) {76 console.warn('Feature unavailable, using fallback');77 return fallback();78 }79}8081// Method 5: Error recovery strategies82class RecoveryStrategy {83 static async retry(fn, maxRetries) {84 // Retry logic85 }8687 static async fallback(fn, fallbackFn) {88 try {89 return await fn();90 } catch (error) {91 return await fallbackFn();92 }93 }9495 static async timeout(fn, timeoutMs, fallback) {96 return Promise.race([97 fn(),98 new Promise((_, reject) =>99 setTimeout(() => reject(new Error('Timeout')), timeoutMs)100 )101 ]).catch(() => fallback());102 }103}
Output
Fetch failed, using fallback: Error Primary failed, using fallback
What's going on
Error recovery maintains functionality.
Fallback Values
Default data
Cached data
Static content
Graceful degradation
Retry with Fallback
Try primary
Retry if fails
Use fallback
Maintain service
Circuit Breaker
Prevent cascading failures
Open on threshold
Half-open for testing
Close on success
Graceful Degradation
Feature unavailable
Use simpler version
Maintain core functionality
User experience
Recovery Strategies
Retry
Fallback
Timeout
Multiple strategies
Best Practices
Plan for failures
Have fallbacks
Monitor recovery
Test strategies