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
Use a general purpose async retry function e.g.
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);