← Back to all snippets
JAVASCRIPT

Add Retry Logic to Robust API Calls in JavaScript

Enhance API call reliability by implementing a customizable retry mechanism with exponential backoff, ensuring resilience against transient network failures.

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) {
                // Only retry on specific server errors or network issues, e.g., 5xx status
                if (response.status >= 500 && response.status < 600 && i < retries - 1) {
                    console.warn(`Attempt ${i + 1} failed (Status: ${response.status}). Retrying in ${delay}ms...`);
                    await new Promise(resolve => setTimeout(resolve, delay));
                    delay *= 2; // Exponential backoff
                    continue;
                }
                const errorData = await response.json().catch(() => ({ message: response.statusText }));
                throw new Error(`HTTP error! Status: ${response.status}, Details: ${errorData.message || 'Unknown error'}`);
            }
            return await response.json();
        } catch (error) {
            if (i < retries - 1 && (error.name === 'TypeError' || error.message.includes('network error'))) {
                // Retry on network errors
                console.warn(`Attempt ${i + 1} failed (Network error). Retrying in ${delay}ms...`);
                await new Promise(resolve => setTimeout(resolve, delay));
                delay *= 2; // Exponential backoff
            } else {
                console.error(`Final attempt failed after ${i + 1} retries:`, error);
                throw error;
            }
        }
    }
    throw new Error('All retry attempts failed.');
}

// Example usage:
async function getReliableData() {
    try {
        const data = await fetchWithRetry('https://api.example.com/unreliable-data');
        console.log('Reliable data:', data);
    } catch (error) {
        console.error('Failed to get reliable data:', error.message);
    }
}

// Call the example function
// getReliableData();
How it works: This snippet provides a robust `fetchWithRetry` function that attempts an API call multiple times with exponential backoff. It's designed to handle transient network issues and specific server errors (like 5xx statuses) by pausing before retrying. This enhances the resilience of your application by making API integrations more tolerant to temporary failures without immediately crashing or showing an error to the user.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs