How to retry 5xx requests using axios
I would like to retry 5xx requests using axios. I have my main request in the middle of a try catch block. I am using the axios-retry library to auto retry 3 times.
The url i am using will deliberately throw a 503. However the request is not being retried, instead it is being caught in my catch block.
axiosRetry(axios, {
retries: 3
});
let result;
const url = "https://httpstat.us/503";
const requestOptions = {
url,
method: "get",
headers: {
},
data: {},
};
try {
result = await axios(requestOptions);
} catch (err) {
throw new Error("Failed to retry")
}
}
return result;
Solution 1:
axios-retry uses axios interceptor to retry HTTP requests. It intercepts requests or responses before they are handled by then or catch. Below is the working code snippet.
const axios = require('axios');
const axiosRetry = require('axios-retry');
axiosRetry(axios, {
retries: 3, // number of retries
retryDelay: (retryCount) => {
console.log(`retry attempt: ${retryCount}`);
return retryCount * 2000; // time interval between retries
},
retryCondition: (error) => {
// if retry condition is not specified, by default idempotent requests are retried
return error.response.status === 503;
},
});
const response = await axios({
method: 'GET',
url: 'https://httpstat.us/503',
}).catch((err) => {
if (err.response.status !== 200) {
throw new Error(`API call failed with status code: ${err.response.status} after 3 retry attempts`);
}
});
Solution 2:
use retry
const retry = require('retry');
const operation = retry.operation({
retries: 5,
factor: 3,
minTimeout: 1 * 1000,
maxTimeout: 60 * 1000,
randomize: true,
});
operation.attempt(async (currentAttempt) => {
console.log('sending request: ', currentAttempt, ' attempt');
try {
await axios.put(...);
} catch (e) {
if (operation.retry(e)) { return; }
}
});
Solution 3:
You can use axios
interceptors to intercept the response and retry the request.
You can intercept requests or responses before they are handled by
then
orcatch
.
See axios interceptors
There are 2 popular packages that already leverage axios
interceptors to do just that:
- axios-retry
- retry-axios
Here's a NPM compare link to help you decide between the two