JAVASCRIPT

Robust API Error Handling in JavaScript

Implement comprehensive error handling for API requests using async/await and try/catch blocks, gracefully managing network issues and server-side errors.

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

    if (!response.ok) {
      let errorInfo = {
        status: response.status,
        statusText: response.statusText,
        message: `API request failed with status ${response.status}`
      };
      
      try {
        // Attempt to parse error details from JSON response body
        const errorData = await response.json();
        errorInfo.message = errorData.message || errorData.error || errorInfo.message;
        errorInfo.details = errorData;
      } catch (jsonError) {
        // If response is not JSON or parsing fails
        errorInfo.message = `API request failed with status ${response.status}: ${response.statusText}`;
      }
      
      throw new Error(JSON.stringify(errorInfo));
    }

    return await response.json();
  } catch (error) {
    if (error.name === 'TypeError' && error.message === 'Failed to fetch') {
      // Network error (e.g., CORS, no internet, invalid URL)
      console.error('Network error or invalid URL:', error);
      throw new Error('Network error: Could not reach the API. Please check your internet connection or the API endpoint.');
    } else if (error.message.includes('API request failed')) {
      // Server-side API error (parsed from response)
      const parsedError = JSON.parse(error.message);
      console.error('API Error:', parsedError);
      throw new Error(`API Error (${parsedError.status}): ${parsedError.message}`);
    } else {
      // Other unexpected errors
      console.error('An unexpected error occurred:', error);
      throw new Error('An unexpected error occurred during the API request.');
    }
  }
}

// Example Usage:
// makeApiRequest('https://api.example.com/non-existent-endpoint')
//   .then(data => console.log('Success:', data))
//   .catch(error => console.error('Request failed:', error.message));

// makeApiRequest('https://invalid-domain-xyz123.com')
//   .catch(error => console.error('Network/Invalid URL error:', error.message));
How it works: This snippet provides a comprehensive error handling strategy for `fetch` API requests. It distinguishes between network errors (e.g., `TypeError` for 'Failed to fetch') and server-side errors (non-`2xx` HTTP status codes). It attempts to parse detailed error messages from the API's JSON response body, ensuring that client applications can display specific and user-friendly error feedback.

Need help integrating this into your project?

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

Hire DigitalCodeLabs