Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retry 5xx requests using axios

Tags:

I would like to retry 5xx requests using axios. I have my main request in the middle of a try catch block. I am using the axios-retry library to auto retry 3 times.

The url i am using will deliberately throw a 503. However the request is not being retried, instead it is being caught in my catch block.

axiosRetry(axios, {   retries: 3 });  let result;  const url = "https://httpstat.us/503"; const requestOptions = {   url,   method: "get",   headers: {   },   data: {}, };   try {    result = await axios(requestOptions);  } catch (err) {   throw new Error("Failed to retry") }  } return result; 
like image 642
Kay Avatar asked May 10 '19 09:05

Kay


People also ask

Does Axios have Retry?

By default, it retries if it is a network error or a 5xx error on an idempotent request (GET, HEAD, OPTIONS, PUT or DELETE). A callback to further control the delay in milliseconds between retried requests.

Which method is used to make multiple concurrent requests Axios?

axios. all is a helper method built into Axios to deal with concurrent requests. Instead of making multiple HTTP requests individually, the axios. all method allows us to make multiple HTTP requests to our endpoints altogether.


1 Answers

axios-retry uses axios interceptor to retry HTTP requests. It intercepts requests or responses before they are handled by then or catch. Below is the working code snippet.

  const axios = require('axios');   const axiosRetry = require('axios-retry');    axiosRetry(axios, {     retries: 3, // number of retries     retryDelay: (retryCount) => {       console.log(`retry attempt: ${retryCount}`);       return retryCount * 2000; // time interval between retries     },     retryCondition: (error) => {       // if retry condition is not specified, by default idempotent requests are retried       return error.response.status === 503;     },   });    const response = await axios({     method: 'GET',     url: 'https://httpstat.us/503',   }).catch((err) => {     if (err.response.status !== 200) {       throw new Error(`API call failed with status code: ${err.response.status} after 3 retry attempts`);     }   }); 
like image 122
ns94 Avatar answered Sep 18 '22 09:09

ns94