Axios is a popular JavaScript library used for making HTTP requests. One of its powerful features is the ability to use interceptors, which can be a game-changer when handling errors effectively. This article will delve deep into how to catch errors using Axios interceptors, providing you with practical examples and insights that will enhance your development experience.
Understanding Axios Interceptors
Axios interceptors allow you to run your code or modify the request or response before the request is sent or after a response is received. This feature is particularly useful for error handling, as you can intercept errors globally instead of repeating error handling logic in multiple places across your application.
Types of Interceptors
There are two types of interceptors in Axios:
-
Request Interceptors: These are functions that intercept requests made by Axios before they are sent. They can be used to modify headers, log request data, or include authentication tokens.
-
Response Interceptors: These interceptors are executed when a response is received from a server. They can transform the response data, handle errors, or log responses.
Setting Up Axios Interceptors
To use Axios interceptors, you need to set them up after creating an Axios instance or directly on the default Axios instance. Here’s a quick example of how to create an Axios instance and set up interceptors.
import axios from 'axios';
// Create an Axios instance
const api = axios.create({
baseURL: 'https://api.example.com',
});
// Add a request interceptor
api.interceptors.request.use(
(config) => {
// Do something before the request is sent
console.log('Request:', config);
return config;
},
(error) => {
// Handle request error
return Promise.reject(error);
}
);
// Add a response interceptor
api.interceptors.response.use(
(response) => {
// Do something with the response data
console.log('Response:', response);
return response;
},
(error) => {
// Handle response error
console.error('Error Response:', error.response);
return Promise.reject(error);
}
);
Important Note:
Always return the config and response objects in your interceptors to ensure that the requests and responses continue to flow through Axios correctly.
Catching Errors with Response Interceptors
Handling errors effectively is essential for building resilient applications. With response interceptors, you can centralize your error handling strategy. Here's how you can manage different types of errors:
Example: Handling Different Error Scenarios
When a request fails, you might want to handle different HTTP status codes distinctly. For instance, a 404 error (not found) might prompt you to redirect the user, while a 500 error (server error) could display a friendly error message.
api.interceptors.response.use(
(response) => {
return response;
},
(error) => {
switch (error.response.status) {
case 404:
console.error('Error: Resource not found.');
// Redirect to a 404 page or show a message
break;
case 500:
console.error('Error: Server error occurred.');
// Show a friendly error message
break;
default:
console.error('Error:', error.message);
}
return Promise.reject(error);
}
);
Logging Errors for Debugging
Logging errors can greatly aid in debugging. You can log the error response, which contains valuable information about the error. Below is an example of enhanced error logging.
api.interceptors.response.use(
(response) => {
return response;
},
(error) => {
console.error('Error occurred:', {
message: error.message,
status: error.response?.status,
data: error.response?.data,
});
return Promise.reject(error);
}
);
Retrying Failed Requests
Sometimes, errors may be transient, such as network issues. In these cases, you might want to retry the request. This can be done using a response interceptor by implementing a simple retry mechanism.
Example: Automatic Retry Logic
You can implement a retry mechanism for certain status codes. Here’s an example of retrying a request:
const MAX_RETRIES = 3;
api.interceptors.response.use(
(response) => {
return response;
},
async (error) => {
const config = error.config;
if (!config) return Promise.reject(error);
// Retry for 5xx status codes
if (error.response && error.response.status >= 500) {
config.__retryCount = config.__retryCount || 0;
if (config.__retryCount < MAX_RETRIES) {
config.__retryCount += 1;
console.log(`Retrying request: ${config.__retryCount}`);
return api(config);
}
}
return Promise.reject(error);
}
);
Important Note:
Ensure to track the retry count to avoid infinite loops in case of persistent errors.
Using Global Error Handling
In addition to interceptors, you might also want to handle errors globally within your application. This can be useful for displaying notifications or alerts to the user.
Example: Displaying Global Notifications
You can create a notification system to inform users of errors:
function displayErrorNotification(message) {
alert(`Error: ${message}`);
}
api.interceptors.response.use(
(response) => {
return response;
},
(error) => {
const message = error.response?.data?.message || error.message || 'An error occurred';
displayErrorNotification(message);
return Promise.reject(error);
}
);
Conclusion
Incorporating Axios interceptors into your application can vastly improve your error handling capabilities. By catching errors at a central point and implementing mechanisms such as retries and global notifications, you can create a better user experience. Remember to customize the error handling according to your application’s needs and always keep your users informed.
By mastering Axios interceptors, you'll be well-equipped to tackle various challenges that arise when dealing with HTTP requests. Happy coding! 🚀