HTTP client with retry — handles transient failures automatically.
1async function fetchWithRetry(url, options = {}, retries = 3) {2 const { delay = 1000, backoff = 2, ...fetchOptions } = options;34 for (let attempt = 0; attempt <= retries; attempt++) {5 try {6 const response = await fetch(url, fetchOptions);78 if (response.ok) return response;910 // Do not retry on client errors (4xx)11 if (response.status >= 400 && response.status < 500) {12 throw new Error(`Client error: ${response.status}`);13 }1415 // Server error — retry16 throw new Error(`Server error: ${response.status}`);17 } catch (err) {18 if (attempt === retries) throw err;1920 const waitTime = delay * Math.pow(backoff, attempt);21 console.log(`Attempt ${attempt + 1} failed, retrying in ${waitTime}ms`);22 await new Promise(r => setTimeout(r, waitTime));23 }24 }25}2627// Usage28const response = await fetchWithRetry("https://api.example.com/data", {29 retries: 3,30 delay: 1000,31 headers: { Authorization: "Bearer token" },32});
Key points: