Last active
August 6, 2021 08:12
-
-
Save flaviu-chelaru/033c20ab244c01953102492ac05fb23b to your computer and use it in GitHub Desktop.
This will allow AXIOS to retry the same request a number of times
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this will make use of axios interceptors | |
// and allow axios to retry SERVER errors | |
// on the initial request we initialize attempt count to 1 | |
// then on each retry we increment the attempt number | |
// we send the attempt number to the server as a custom header (x-attempt) | |
axios.interceptors.request.use((request: AxiosRequestConfig) => { | |
request.headers.common = { | |
'x-attempt': request.headers.common['x-attempt'] || 1 | |
}; | |
// @todo add aditional stuff: add random user agent, add proxy, etc | |
console.log(new Date(), 'requesting', request.url); | |
return request; | |
}); | |
axios.interceptors.response.use( | |
response => response, | |
err => { | |
// i only retry server errors. client errors i allow to fail | |
if (err && err.response && err.response.status < 500) { | |
return Promise.reject(err) | |
} | |
let attempt = err.config.headers['x-attempt'] || 1; | |
const tries = 5; | |
if (attempt < tries) { | |
err.config.headers['x-attempt'] = attempt + 1; | |
console.log(new Date(), `retrying ${attempt}/${tries}..`, err.config.url) | |
return axios.request(err.config); | |
} | |
return Promise.reject(err); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment