API Error Handling

What is API error handling?

API error handling gracefully manages failures when communicating with servers, preventing crashes and providing user feedback.

Benefits of API error handling?

  • Prevent app crashes
  • Display error messages to users
  • Retry failed requests
  • Handle network issues
  • Provide fallback data
// API with error handling
async function fetchGameData(url) {
    try {
        const response = await fetch(url);
        
        // Check for network errors
        if (!response.ok) {
            throw new Error(`API error: ${response.status}`);
        }
        
        const data = await response.json();
        return data;
    } catch (error) {
        // Handle different error types
        if (error instanceof TypeError) {
            console.error("Network error:", error);
        } else if (error instanceof SyntaxError) {
            console.error("JSON parsing error:", error);
        } else {
            console.error("Unknown error:", error);
        }
        
        // Return default/fallback data
        return null;
    }
}

What does this code do?

  • Wraps API call in try-catch block
  • Checks response status
  • Distinguishes between different error types
  • Handles network errors separately from JSON errors
  • Returns null as fallback instead of crashing
  • Provides clear error messages for debugging
// Retry failed requests with exponential backoff
async function fetchWithRetry(url, maxRetries = 3) {
    let retryCount = 0;
    
    while (retryCount < maxRetries) {
        try {
            const response = await fetch(url);
            
            if (response.ok) {
                return await response.json();
            } else if (response.status === 429) {
                // Rate limited - wait and retry
                const waitTime = Math.pow(2, retryCount) * 1000;
                console.log(`Rate limited. Waiting ${waitTime}ms...`);
                await new Promise(resolve => setTimeout(resolve, waitTime));
                retryCount++;
            } else {
                throw new Error(`HTTP ${response.status}`);
            }
        } catch (error) {
            console.error(`Attempt ${retryCount + 1} failed:`, error);
            retryCount++;
            
            if (retryCount >= maxRetries) {
                console.error("Max retries reached");
                return null;
            }
        }
    }
}

What does this code do?

  • Retries failed requests automatically
  • Implements exponential backoff (wait longer each retry)
  • Detects rate limiting (429 status)
  • Limits retries to prevent infinite loops
  • Returns null if all retries fail
  • Shows production-quality error handling

layout: post title: API Error Handling description: Learn about API Error Handling permalink: /api_error_handling author: Vihaan Budhraja —

Try It Yourself

%%js // CODE_RUNNER: api-error-handling async function fetchData() { try { const response = await fetch(‘https://jsonplaceholder.typicode.com/users/1’); if (!response.ok) throw new Error(‘HTTP error’); const data = await response.json(); console.log(“Data: “ + data.name); } catch (error) { console.error(“Error: “ + error.message); } } fetchData();