Skip to content

Instantly share code, notes, and snippets.

@flaviu-chelaru
Last active August 6, 2021 08:12
Show Gist options
  • Save flaviu-chelaru/033c20ab244c01953102492ac05fb23b to your computer and use it in GitHub Desktop.
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 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