nukiko12
nukiko12

Reputation: 149

Axios - setup interceptor to retry original request on error

I need to setup a global interceptor for all my axios calls. I'm defining them inside vuex actions and I need that if there is a 429 status code, an action is called and then after that actions is made, a retry with the original request is made. I'm learning about interceptors but I don't know how to properly setup it,and if it will work outside the export default. Can anyone help me?

axios.interceptors.use( (response) => {
// if no status error code is returned get the response
  return response
}, (error) => {
  console.log(error)
  // here I need to retry the ajax call after that my loadProxy action is made and a 429 status code is sent from the server
  return Promise.reject(error);
})

export default new Vuex.Store({
 actions: {
  loadProxy({ commit }) {
  // here I have an axios get request to fetch a proxy from an API 
  },
  fetchData({ commit, state }) {
  // here I fetch the data to use in my app, sometimes due to many requests I need to refresh the proxy ip to let the app continue working
  }
 }
})

Upvotes: 3

Views: 15022

Answers (2)

hawschiat
hawschiat

Reputation: 336

The response object in Axios' interceptor contains a config object. (See here)

You can use that to re-initiate the request with the original configuration.

An example:

axios.interceptors.response.use((response) => {
    return response;
}, (error) => {
    if (error.response.status === 429) {
        // If the error has status code 429, retry the request
        return axios.request(error.config);
    }
    return Promise.reject(error);
});

To use a Vuex action inside the interceptor callback, you can first define the store as a variable, then call the dispatch function inside the callback. Like this:

const store = new Vuex.Store({
   // define store...
})

axios.interceptors.response.use((response) => {
    return response;
}, (error) => {
    if (error.response.status === 429) {
        store.dispatch("YOUR_ACTION");
        return axios.request(error.config);
    }
    return Promise.reject(error);
});

export default store;

Upvotes: 11

hgb123
hgb123

Reputation: 14891

You could have a experiment with axios-retry, there is a option

retryCondition: A callback to further control if a request should be retried

import axiosRetry from "axios-retry"

// ...

// intercept
axiosRetry(axios, {
  retries: 3,
  retryCondition: (error) => {
    return error.response.status === 429
  },
})

Upvotes: 4

Related Questions