Error Recovery in JavaScript
Recover from errors in JavaScript with fallback values, retry then fallback, a circuit breaker, graceful degradation and timeouts. Explanation and output.
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'))70 .catch(() => console.log('Breaker state:', breaker.state, '| failures:', breaker.failures));7172// Method 4: Graceful degradation73function featureWithFallback(feature, fallback) {74 try {75 return feature();76 } catch (error) {77 console.warn('Feature unavailable, using fallback');78 return fallback();79 }80}8182// Method 5: Error recovery strategies83class RecoveryStrategy {84 static async retry(fn, maxRetries) {85 // Retry logic86 }8788 static async fallback(fn, fallbackFn) {89 try {90 return await fn();91 } catch (error) {92 return await fallbackFn();93 }94 }9596 static async timeout(fn, timeoutMs, fallback) {97 return Promise.race([98 fn(),99 new Promise((_, reject) =>100 setTimeout(() => reject(new Error('Timeout')), timeoutMs)101 )102 ]).catch(() => fallback());103 }104}
Sample Output
Breaker state: CLOSED | failures: 1
One failure is below the threshold of 5, so the breaker stays CLOSED. Four more failures would open it.
In this one
- How to return a fallback value when a call fails
- How a circuit breaker moves between CLOSED, OPEN and HALF_OPEN
- What graceful degradation means
- How Promise.race adds a timeout
How it works
- 1
A CircuitBreaker starts CLOSED with 0 failures.
- 2
execute calls fetch, which fails.
- 3
onFailure raises failures to 1.
- 4
The error is thrown to the caller.
- 5
The .catch prints the state and count.
Circuit breaker states
How failures change the breaker state.
- 1.Start: failures 0, state CLOSED.
- 2.fetch fails: failures 1, still CLOSED.
- 3.Four more failures: failures 5, state OPEN. Calls fail fast for 60 seconds.
- 4.After 60 seconds: HALF_OPEN. One test call is allowed.
- 5.The test call works: failures 0, state CLOSED.
Edge cases
Fallback hides real outages
Users see old data and nobody notices the server is down.
Log every fallback so you can spot outages.
Breaker never closes
HALF_OPEN calls keep failing, so it opens again each time.
This is correct. Fix the service, and it closes on the next success.
What's going on
Catching an error is only half the job. The app should still be useful afterwards. Error recovery means choosing what to do next, like showing saved data or turning off one feature. JavaScript gives you several patterns for this.
Method 1 returns a fallback value when fetch fails. For example, show the last saved weather instead of a blank screen.
Method 2 tries the main operation a few times. If every try fails, it calls a fallback function, such as a backup server.
Method 3 is a circuit breaker. It works like the breaker in a house. It has three states. CLOSED means calls go through normally. After a set number of failures, the threshold (5 here), it switches to OPEN. While OPEN, it fails fast without even calling the server, which stops a broken service from being flooded. After the timeout it moves to HALF_OPEN and allows one test call. Success closes it again.
In this run one fetch fails, so failures becomes 1. That is below 5, so the state stays CLOSED. The .catch prints the state and the failure count, so the failure is handled.
Method 4 is graceful degradation. If a feature fails, the app uses a simpler version. Method 5 groups strategies in a class. Its timeout method uses Promise.race, which settles with whichever promise finishes first, so a slow call is replaced by the fallback. Methods 1, 2, 4 and 5 are defined but not called, so only the breaker prints.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does an OPEN breaker do?
Pick an answer to check it.
Question 2
Why is the state CLOSED after one failure?
Pick an answer to check it.
Questions people ask
When should I use a circuit breaker?
When you call another service that may go down and you want to fail fast.
Does Promise.race cancel the slow call?
No. It ignores the late result. Use AbortController to cancel a fetch.
Is a fallback the same as a retry?
No. A retry tries again. A fallback gives a different answer.