Home > Software engineering >  Is it possible to add a retry method to axios response inteceptor?
Is it possible to add a retry method to axios response inteceptor?

Time:12-30

graphqlInstance.interceptors.response.use(response => {
  if (response?.data?.errors) {
    const err = response?.data?.errors?.[0];
    const extension = response?.data?.errors?.[0]?.extensions;
    if (extension?.statusCode === 401 || err?.message === "401 : [no body]") {
      // retry
    }
  }
  return response;
});

In the response part, I need to call the previous request if the API response returns 401.

Note:

  • I'm using graphql which returns a "200 OK" response code for exceptions that's why I m trying to handle the retry method in the success part.

Need to call the previous request if API returns 401.

CodePudding user response:

do axios.request

if (extension?.statusCode === 401 || err?.message === "401 : [no body]") {
   return axios.request(response.config);

}

CodePudding user response:

Axios Interceptor takes two callbacks as its arguments.

  1. First callback runs in the success situations, when status code is within 2xx.
  2. Second callback runs in the error situations.

I think you should write like this:

graphqlInstance.interceptors.response.use(response => {
//Success code
},error => {
    if (error?.config) {
       Axios.request(error?.config);
    }
  }
});
  • Related