我想使用axios重试5xx请求。我的主请求位于try catch块的中间。我正在使用axios-retry库自动重试3次。
我使用的url会故意抛出一个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;
发布于 2020-09-26 18:34:14
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`);
}
});
发布于 2019-05-10 17:49:03
使用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; }
}
});
发布于 2019-08-26 17:28:44
您可以使用axios
拦截器拦截响应并重试请求。
您可以在
then
或catch
处理请求或响应之前对其进行拦截。
有两个流行的包已经利用axios
拦截器来做到这一点:
这里有一个NPM compare链接,可以帮助您在两者之间做出选择
https://stackoverflow.com/questions/56074531
复制相似问题