JAVASCRIPT
Centralized API Error Handling with Axios Interceptors
Streamline error management across your application by implementing a global interceptor to catch and process API errors consistently using Axios.
import axios from 'axios';
// Create an Axios instance
const apiClient = axios.create({
baseURL: 'https://api.example.com',
timeout: 10000, // 10 seconds
headers: {
'Content-Type': 'application/json',
},
});
// Add a response interceptor
apiClient.interceptors.response.use(
(response) => {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
},
(error) => {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.error('API Error Response:', error.response.status, error.response.data);
switch (error.response.status) {
case 401:
console.warn('Unauthorized: Redirecting to login or refreshing token.');
// Example: Redirect to login page or dispatch a logout action
// window.location.href = '/login';
break;
case 403:
console.error('Forbidden: User does not have necessary permissions.');
// Example: Show a permission denied message
break;
case 404:
console.error('Not Found: The requested resource does not exist.');
// Example: Show a generic "resource not found" message
break;
case 500:
console.error('Server Error: Something went wrong on the server.');
// Example: Log error, show a generic error message to user
break;
default:
// Generic error handling
console.error(`Unhandled API Error (${error.response.status}):`, error.response.data);
}
} else if (error.request) {
// The request was made but no response was received
console.error('No API Response:', error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.error('Axios Request Error:', error.message);
}
return Promise.reject(error);
}
);
// Example Usage:
// apiClient.get('/users/1')
// .then(response => console.log('User data:', response.data))
// .catch(error => console.error('Caught by caller:', error.message)); // Specific errors handled by interceptor
How it works: Axios interceptors allow you to globally catch and handle HTTP requests and responses before they are processed by `then` or `catch` blocks. This snippet demonstrates a response interceptor that centralizes error handling for common API issues like authentication failures (401), permission errors (403), or server errors (500). By setting this up, you avoid repetitive error handling logic in every API call, ensuring consistency and making your codebase cleaner and more maintainable.