简体   繁体   中英

How to use axios client to retry on 5xx errors

I am trying add retry to my api call using axios-retry module. In order to test I am using mockoon macosx client. I have setup the endpoint in mockoon to return 502 response all the time. So that I can test the retry.

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')
})()

The issue here is, the axios.get not completing the execution. Therefore it does not log either api call error or api call completed messages. Any help would be highly appreciated.

axiosRetry does not work with axios 0.19.0 (the current axios release) : https://github.com/softonic/axios-retry#note

Alternative

Use a general purpose async retry function eg

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

More

Source of the retry function .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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