javascript - 如何使用axios客户端重试5xx错误

标签 javascript node.js typescript axios axios-retry

我正在尝试使用 axios-retry 模块向我的 api 调用添加重试。为了测试我正在使用 mockoon macosx 客户端。我在 mockoon 中设置了端点以始终返回 502 响应。以便我可以测试重试。

import axios from "axios";
import axiosRetry from 'axios-retry';

async function sendRequest(method): Promise<any> {
  try {

    // return 502 after 100ms
    let url = `http://localhost:3000/answer`

    axiosRetry(axios, {
      retries: 3
    });


    const response = await axios[method](url);
    console.log('api call completed');
    return response;

  } catch (error) {
    console.log('api call error: ', error);
    throw error;
  }
}

(async () => {
  const response = await sendRequest('get')
})()

这里的问题是,axios.get 没有完成执行。因此,它不会记录 api 调用错误api 调用已完成 消息。任何帮助将不胜感激。

最佳答案

axiosRetry 不适用于 axios 0.19.0(当前的 axios 版本):https://github.com/softonic/axios-retry#note

备选

使用通用的异步重试函数,例如

async function retry<T>(fn: () => Promise<T>, n: number): Promise<T> {
  let lastError: any;
  for (let index = 0; index < n; index++) {
    try {
      return await fn();
    }
    catch (e) {
      lastError = e;
    }
  }
  throw lastError;
}

// use 
const response = await retry(() => axios[method](url), 3);

更多

Source of the retry function .

关于javascript - 如何使用axios客户端重试5xx错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59366972/

相关文章:

javascript - JSON.解析 : unexpected non-whitespace character after JSON data in javascript

javascript - 有没有办法用Python解密AES?

javascript - 如何将ASCII码字符串转换为字符串?

node.js - 在 Node.js 中操作从数据库中获取的数字的最佳/最合适的方法

node.js - 覆盖 NPM 项目的 `npm install` 脚本

javascript - Uncaught ReferenceError : io is not defined

隐式类型转换的 TypeScript 错误

Javascript:绑定(bind)到函数的右侧?

node.js - 在 Jest 的不同环境中运行相同的测试

typescript - 将类型指定为某个字符串文字