我想使用axios重试5xx请求。我的主要要求是在try catch块中间。我正在使用axios-retry库自动重试3次。
我正在使用的网址会故意抛出503。但是不会重试该请求,而是将其捕获到我的catch块中。
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;
答案 0 :(得分:2)
axios-retry使用axios interceptor重试HTTP请求。它会先拦截请求或响应,然后再由then或catch处理。 下面是工作代码段。
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`);
}
});
答案 1 :(得分:2)
您可以使用 axios.interceptors.response.use
来做到这一点。当您遇到错误时,您可以使用 axios
递归返回 resolve
请求。然后你可以自己定义条件,只要你想重试。这是一个简单的 axios 重试版本,这也是 axios-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) => {
/** @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()
我也做了一个demo版本来模拟最终请求成功,但是之前的请求都失败了。我定义了status_code: 404 我想重试,设置3次重试
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()
您将看到打印出以下消息的日志。
==================
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' }
答案 2 :(得分:0)
使用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; }
}
});
答案 3 :(得分:0)
您可以使用axios
拦截器来拦截响应并重试请求。
在
then
或catch
处理请求或响应之前,您可以拦截它们。
有2种流行的软件包已经利用axios
拦截器来做到这一点:
这里有一个NPM compare链接,可帮助您在两者之间做出决定
答案 4 :(得分:0)
您可以通过不使用其他库来做到这一点。
new Promise(async (resolve, reject) => {
let retries = 0;
const maxRetries = 3;
while (retries < maxRetries) {
try {
const response = await axios(options);
resolve(response.data);
} catch (err) {
const status = err?.response?.status || 500;
console.log(`Error Status: ${status}`);
}
}
console.log(`Too many request retries.`);
reject()
})
答案 5 :(得分:0)
更新 Andrien 答案以防止进程泄漏。一旦请求成功,我们应该停止循环,并且忘记放置增量,因此这意味着它永远不会停止循环。这只会在请求失败且最大为 3 时重试。您可以通过根据您的首选值更改 maxRetries
来增加它。
new Promise(async (resolve, reject) => {
let retries = 0;
const maxRetries = 3;
const success = false
while (retries < maxRetries && !success) {
try {
const response = await axios(options);
success = true
resolve(response.data);
} catch (err) {
const status = err?.response?.status || 500;
console.log(`Error Status: ${status}`);
}
retries++
}
console.log(`Too many request retries.`);
reject()
})
有关更多详细信息,请查看 while 循环的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while