如何使用 axios 重试 5xx 请求

Kay*_*Kay 22 node.js axios

我想使用 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;
Run Code Online (Sandbox Code Playgroud)

sha*_*359 24

axios-retry使用 axios拦截器重试 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`);
    }
  });
Run Code Online (Sandbox Code Playgroud)

  • https://developer.mozilla.org/en-US/docs/Glossary/Idempotency (5认同)

Jac*_* Yu 18

你可以用来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()
Run Code Online (Sandbox Code Playgroud)

我还做了一个演示版本来模拟最终请求成功,但之前的请求全部失败。我定义了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()
Run Code Online (Sandbox Code Playgroud)

您将看到日志打印以下消息。

==================
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' }
Run Code Online (Sandbox Code Playgroud)


Jun*_* L. 13

使用重试

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; }
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 最后一个实际有效的例子 - 谢谢! (2认同)

小智 9

更新 Andrien 答案以防止进程泄漏。一旦请求成功,我们应该停止循环,并且忘记添加增量,因此这意味着它永远不会停止循环。仅当请求失败且最多为 3 时,才会重试。您可以maxRetries根据您的首选值进行更改来增加该值。

new Promise(async (resolve, reject) => {
  let retries = 0;
  let success = false;
  const maxRetries = 3;

  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()
})
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请查看 while 循环的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while


Nex*_*ddo 7

您可以使用axios拦截器来拦截响应并重试请求。

您可以在请求或响应由then或处理之前拦截它们catch

查看axios 拦截器


有 2 个流行的软件包已经利用axios拦截器来做到这一点:

这是一个NPM 比较链接,可帮助您在两者之间做出决定