You could use axios.interceptors.response.use
to do that. When you encounter the error, you could recursive return axios
request with resolve
. Then you could defined the condition by youself whenever you want to retry. This is a simple axios retry version, and this is also a concept which axios-retry do.
const axios = require("axios")
/**
*
* @param {import("axios").AxiosInstance} axios
* @param {Object} options
* @param {number} options.retry_time
* @param {number} options.retry_status_code
*/
const retryWrapper = (axios, options) => {
const max_time = options.retry_time;
const retry_status_code = options.retry_status_code;
let counter = 0;
axios.interceptors.response.use(null, (error) => {
/** @type {import("axios").AxiosRequestConfig} */
const config = error.config
// you could defined status you want to retry, such as 503
// if (counter < max_time && error.response.status === retry_status_code) {
if (counter < max_time) {
counter++
return new Promise((resolve) => {
resolve(axios(config))
})
}
return Promise.reject(error)
})
}
async function main () {
retryWrapper(axios, {retry_time: 3})
const result = await axios.get("https://api.ipify.org?format=json")
console.log(result.data);
}
main()
I also make a demo version to simulate the final request is success, but previous request all failed. I defined the status_code: 404 I want to retry, and setup 3 times for retry.
const axios = require("axios")
/**
*
* @param {import("axios").AxiosInstance} axios
* @param {Object} options
* @param {number} options.retry_time
* @param {number} options.retry_status_code
*/
const retryWrapper = (axios, options) => {
const max_time = options.retry_time;
const retry_status_code = options.retry_status_code;
let counter = 0;
axios.interceptors.response.use(null, (error) => {
console.log("==================");
console.log(`Counter: ${counter}`);
console.log("Error: ", error.response.statusText);
console.log("==================");
/** @type {import("axios").AxiosRequestConfig} */
const config = error.config
if (counter < max_time && error.response.status === retry_status_code) {
counter++
return new Promise((resolve) => {
resolve(axios(config))
})
}
// ===== this is mock final one is a successful request, you could delete one in usage.
if (counter === max_time && error.response.status === retry_status_code) {
config.url = "https://api.ipify.org?format=json"
return new Promise((resolve) => {
resolve(axios(config))
})
}
return Promise.reject(error)
})
}
async function main () {
retryWrapper(axios, {retry_time: 3, retry_status_code: 404})
const result = await axios.get("http://google.com/not_exist")
console.log(result.data);
}
main()
You will see the log print following message.
==================
Counter: 0
Error: Not Found
==================
==================
Counter: 1
Error: Not Found
==================
==================
Counter: 2
Error: Not Found
==================
==================
Counter: 3
Error: Not Found
==================
{ ip: 'x.x.x.x' }