繁体   English   中英

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

[英]How to use axios client to retry on 5xx errors

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

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);

更多的

重试函数的来源

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM