JAVASCRIPT
Implementing a Simple Retry for Transient API Errors
Learn to implement a basic retry mechanism for API calls in JavaScript to handle temporary network issues or server-side glitches, improving application resilience.
async function fetchWithRetry(url, options = {}, retries = 3, delay = 1000) {
for (let i = 0; i <= retries; i++) {
try {
const response = await fetch(url, options);
if (response.ok) {
return response;
} else if (response.status >= 500 && i < retries) {
console.warn(`Attempt ${i + 1} failed with status ${response.status}. Retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
} else {
// Not a 5xx error or max retries reached, throw the original response
throw new Error(`API request failed with status ${response.status}: ${response.statusText}`);
}
} catch (error) {
if (i < retries) {
console.error(`Attempt ${i + 1} failed: ${error.message}. Retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
} else {
throw error; // Max retries reached, rethrow the error
}
}
}
}
// Usage example:
// fetchWithRetry('https://api.example.com/data', { method: 'GET' })
// .then(response => response.json())
// .then(data => console.log('Data fetched:', data))
// .catch(error => console.error('Failed after multiple retries:', error.message));
How it works: This JavaScript function `fetchWithRetry` wraps the standard `fetch` API call, adding a simple retry mechanism. It attempts to make the API request a specified number of times, with a fixed delay between retries. It specifically retries on network errors or server-side 5xx status codes, which often indicate transient issues. If all retries fail, it rethrows the last error, ensuring the application can gracefully handle persistent failures.