JAVASCRIPT

Centralized Error Handling for API Responses

Implement robust, centralized error handling for your API calls using JavaScript's Fetch API, catching network issues and parsing HTTP status codes.

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

    if (!response.ok) {
      let errorMessage = `HTTP error! Status: ${response.status}`;
      try {
        const errorBody = await response.json();
        errorMessage += `, Details: ${errorBody.message || JSON.stringify(errorBody)}`;
      } catch (e) {
        // If response is not JSON, use status text or default
        errorMessage += `, Details: ${response.statusText || 'No detailed error message'}`;
      }
      throw new Error(errorMessage);
    }

    return await response.json();
  } catch (error) {
    console.error('API call failed:', error.message);
    // Optionally, re-throw or handle specific error types (e.g., network down)
    throw error;
  }
}

// Example usage:
// safeApiCall('https://api.example.com/data')
//   .then(data => console.log('Data fetched:', data))
//   .catch(error => console.error('Error in API call:', error.message));

// safeApiCall('https://api.example.com/non-existent-endpoint')
//   .catch(error => console.error('Error fetching non-existent:', error.message));
How it works: This snippet provides a centralized utility function for making API calls with comprehensive error handling. It checks the `response.ok` property to identify non-2xx HTTP responses. If an error occurs, it attempts to parse the response body as JSON to extract detailed error messages from the API, falling back to status text if the response isn't JSON. This approach makes API interactions more reliable and provides clearer debug information, improving the user experience.

Need help integrating this into your project?

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

Hire DigitalCodeLabs