Error Handling and Retry Strategy with Axios Interceptors
Implement a custom Axios interceptor that retries failed requests with exponential backoff, which is useful for flaky API connections.
const axios = require('axios');
// Define the maximum number of retries
const MAX_RETRIES = 3;
// Axios interceptor for retrying requests with exponential backoff
axios.interceptors.response.use(null, async (error) => {
const config = error.config;
// If config does not exist or the retry option is not set, reject
if (!config || !config.retry) return Promise.reject(error);
// Set the retry count if it's not defined
config.__retryCount = config.__retryCount || 0;
// Check if we've maxed out the total number of retries
if (config.__retryCount >= MAX_RETRIES) return Promise.reject(error);
// Increase the retry count
config.__retryCount += 1;
// Calculate the exponential backoff delay
const backoffDelay = (2 ** config.__retryCount) * 1000;
// Return a promise that resolves after the backoff delay
return new Promise((resolve) => setTimeout(() => resolve(axios(config)), backoffDelay));
});
// Now you can use axios to make requests with the retry strategy
// axios.get('/your/api/endpoint', { retry: true })
This code defines an Axios interceptor that intercepts any failed HTTP response. When a request fails, it checks if the retry option is set and that the maximum number of retries has not been reached. If it's eligible for retry, it waits for an exponentially increasing delay before retrying the request. The `MAX_RETRIES` constant dictates how many times to retry, and the delay is calculated with a simple exponential backoff formula.