JAVASCRIPT

Implement Robust Error Handling for Fetch API Calls

Enhance API call reliability by implementing comprehensive error handling with JavaScript's Fetch API, checking response status and parsing API-specific error bodies.

async function safeFetch(url, options = {}) {
  try {
    const response = await fetch(url, options);

    // Check for HTTP success status (200-299)
    if (!response.ok) {
      let errorDetails = {};
      try {
        // Attempt to parse JSON error body if available
        errorDetails = await response.json();
      } catch (e) {
        // If parsing fails, use statusText or a generic message
        errorDetails = { message: response.statusText || 'Unknown API Error' };
      }
      const errorMessage = `API Request Failed: ${response.status} - ${errorDetails.message || JSON.stringify(errorDetails)}`;
      throw new Error(errorMessage);
    }

    // Attempt to parse JSON response
    const data = await response.json();
    return data;

  } catch (networkError) {
    // Catch network-related errors (e.g., no internet connection, DNS failure)
    console.error('Network or CORS error during fetch:', networkError);
    throw new Error(`Network Error: ${networkError.message}`);
  }
}

// Usage example:
// safeFetch('https://api.example.com/nonexistent-endpoint')
//   .then(data => console.log('Data:', data))
//   .catch(error => console.error('Caught error in usage:', error.message));
//
// safeFetch('https://jsonplaceholder.typicode.com/todos/1')
//   .then(data => console.log('Successfully fetched:', data))
//   .catch(error => console.error('Caught error in usage:', error.message));
How it works: This snippet provides a robust pattern for handling errors in Fetch API calls. It differentiates between network errors (caught by the `try...catch` block) and HTTP response errors (checked by `response.ok`). For HTTP errors, it attempts to parse the response body for API-specific error messages, falling back to general messages if parsing fails or no message is provided. This ensures comprehensive feedback on API integration issues.

Need help integrating this into your project?

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

Hire DigitalCodeLabs