Error Retry Logic in JavaScript
Implement retry logic for failed operations
IntermediateError HandlingExample 7 of 10
error-retry-logic.js
1// Method 1: Simple retry2async function retryOperation(fn, maxRetries = 3) {3 for (let i = 0; i < maxRetries; i++) {4 try {5 return await fn();6 } catch (error) {7 if (i === maxRetries - 1) throw error;8 console.log(`Retry ${i + 1} failed, retrying...`);9 await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));10 }11 }12}1314// Method 2: Retry with exponential backoff15async function retryWithBackoff(fn, maxRetries = 3, baseDelay = 1000) {16 for (let i = 0; i < maxRetries; i++) {17 try {18 return await fn();19 } catch (error) {20 if (i === maxRetries - 1) throw error;21 const delay = baseDelay * Math.pow(2, i);22 console.log(`Retry ${i + 1} after ${delay}ms`);23 await new Promise(resolve => setTimeout(resolve, delay));24 }25 }26}2728// Method 3: Retry with conditions29async function retryWithCondition(fn, shouldRetry, maxRetries = 3) {30 for (let i = 0; i < maxRetries; i++) {31 try {32 return await fn();33 } catch (error) {34 if (!shouldRetry(error) || i === maxRetries - 1) {35 throw error;36 }37 await new Promise(resolve => setTimeout(resolve, 1000));38 }39 }40}4142// Usage43retryWithCondition(44 () => fetch('https://api.example.com/data'),45 (error) => error.message.includes('network') || error.message.includes('timeout'),46 347);4849// Method 4: Retry class50class RetryHandler {51 constructor(options = {}) {52 this.maxRetries = options.maxRetries || 3;53 this.delay = options.delay || 1000;54 this.backoff = options.backoff || 'exponential';55 }5657 async execute(fn) {58 for (let i = 0; i < this.maxRetries; i++) {59 try {60 return await fn();61 } catch (error) {62 if (i === this.maxRetries - 1) throw error;6364 const delay = this.calculateDelay(i);65 await this.wait(delay);66 }67 }68 }6970 calculateDelay(attempt) {71 if (this.backoff === 'exponential') {72 return this.delay * Math.pow(2, attempt);73 }74 return this.delay;75 }7677 wait(ms) {78 return new Promise(resolve => setTimeout(resolve, ms));79 }80}8182const retryHandler = new RetryHandler({ maxRetries: 3, delay: 1000 });83retryHandler.execute(() => fetch('https://api.example.com/data'));
Output
Retry 1 failed, retrying... Retry 2 failed, retrying... Retry 1 after 1000ms Retry 2 after 2000ms
What's going on
Retry logic handles transient failures.
Simple Retry
Fixed attempts
Fixed delay
Re-throw on failure
Exponential Backoff
Increasing delays
1s, 2s, 4s, etc.
Reduces load
Conditional Retry
Check error type
Retry only certain errors
Skip others
Retry Class
Configurable
Reusable
Flexible
Use Cases
Network requests
Database operations
External APIs
Transient failures
Best Practices
Limit retries
Use backoff
Check error types
Don't retry forever