【问题标题】:How to use axios client to retry on 5xx errors如何使用axios客户端重试5xx错误
【发布时间】:2020-04-09 12:39:25
【问题描述】:

我正在尝试使用 axios-retry 模块向我的 api 调用添加重试。为了测试我正在使用mockoonmacosx 客户端。我已经在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 call errorapi call completed 消息。任何帮助将不胜感激。

【问题讨论】:

    标签: javascript node.js typescript axios axios-retry


    【解决方案1】:

    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.

    【讨论】:

    • 如何在尝试之间引入延迟。
    • 您可以使用 mockswitch 应用添加延迟。
    猜你喜欢
    • 1970-01-01
    • 2018-03-09
    • 2020-12-18
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    相关资源
    最近更新 更多