JAVASCRIPT

Centralized Error Handling for API Requests

Implement a robust and centralized error handling mechanism for all API requests using Axios interceptors, distinguishing between network, client (4xx), and server (5xx) errors.

import axios from 'axios';

const api = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 10000, // Request timeout after 10 seconds
  headers: {
    'Content-Type': 'application/json',
  },
});

// Add a response interceptor for centralized error handling
api.interceptors.response.use(
  response => response, // If the response is successful, just return it
  error => {
    let errorInfo = {
      type: 'UNKNOWN_ERROR',
      message: 'An unexpected error occurred.',
      details: error.message,
      status: null,
      code: null,
    };

    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      errorInfo.status = error.response.status;
      errorInfo.details = error.response.data || error.message;

      if (error.response.status >= 400 && error.response.status < 500) {
        errorInfo.type = 'CLIENT_ERROR'; // e.g., 400 Bad Request, 401 Unauthorized, 404 Not Found
        errorInfo.message = `Client Error (${error.response.status})`;
        errorInfo.code = error.response.data?.code || null;
      } else if (error.response.status >= 500 && error.response.status < 600) {
        errorInfo.type = 'SERVER_ERROR'; // e.g., 500 Internal Server Error, 503 Service Unavailable
        errorInfo.message = `Server Error (${error.response.status})`;
        errorInfo.code = error.response.data?.code || null;
      }
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an http.ClientRequest in node.js
      errorInfo.type = 'NETWORK_ERROR';
      errorInfo.message = 'Network Error: No response received.';
      errorInfo.details = error.message;
    } else {
      // Something happened in setting up the request that triggered an Error
      errorInfo.type = 'REQUEST_SETUP_ERROR';
      errorInfo.message = 'Error setting up the request.';
      errorInfo.details = error.message;
    }

    console.error('API Error:', errorInfo);
    // You can also throw a custom error or dispatch an event here
    // throw new CustomAPIError(errorInfo);
    return Promise.reject(errorInfo); // Re-throw the structured error for further handling
  }
);

export default api;

// Example Usage (in another file):
// import api from './apiConfig'; // Assuming apiConfig.js contains the above setup
// async function fetchData() {
//   try {
//     const response = await api.get('/data');
//     console.log('Data:', response.data);
//   } catch (error) {
//     console.error('Caught in component/service:', error.message);
//     // Specific handling based on error.type or error.status
//     if (error.type === 'NETWORK_ERROR') {
//       alert('Please check your internet connection.');
//     } else if (error.status === 401) {
//       alert('You are unauthorized. Please log in.');
//     }
//   }
// }
// fetchData();
How it works: This JavaScript snippet sets up a centralized error handling mechanism for API requests using Axios interceptors. It categorizes errors into `CLIENT_ERROR` (4xx status), `SERVER_ERROR` (5xx status), `NETWORK_ERROR` (no response), or `REQUEST_SETUP_ERROR`. This structured approach allows developers to handle different types of API failures consistently across their application, improving reliability and 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