Get notified after axios timeout
Solution 1
Axios errors are identified by code
property.
It's ECONNABORTED
code in case of a timeout.
The code above uses promise construction antipattern. There's already a promise, no need to create a new one:
_post(url, body, token) {
return instance
.post(url, body, {headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}})
.catch(error => {
if (error.code === 'ECONNABORTED')
return 'timeout';
else
throw error;
});
}
Solution 2
I know that this is an old post but I had the same problem and the following may help others
I could not get the codepen example above to run
In my case I put the timeout on the axios class rather than the instance
axios.defaults.timeout = 30000
axios.defaults.timeoutErrorMessage='timeout'
I suspect that the reason that you didn't get an error out of it was that you were still looking at e.response.data, in your error handler which presumably gets called at a higher level. On the error object e, e.response.data, does not exist in the case of a timeout so accessing this causes an error in your error handler - at least that is what happened in my case.
With the above I can just check for if(e.message == 'timeout') and then display a special error message
sajithneyo
Updated on July 09, 2022Comments
-
sajithneyo almost 2 years
I have an API call using axios. A timeout is set for 2500 millis. What I want is axios to return a value after the timeout so I can notify to the user the request is aborted due to some server or network error.
How I initialized the timeout
const instance = axios.create(); instance.defaults.timeout = 2500;
Below is the function that should return a value after the timeout
_post(url, body, token) { return new Promise((resolve, reject) => { instance .post(url, body, {headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }}) .then(data => { resolve(data); }) .catch(error => { reject(error); }); }); }
Thank you!
-
sajithneyo almost 6 yearsWell this method does not show any errors after 2.5 seconds.
-
Estus Flask almost 6 yearsIt's unknown whether there are timeouts in your case. But it does, codepen.io/anon/pen/yENBmR?editors=1010 .
-
Ilan.b over 2 yearsNot sure about that but from the documentation they right about clarifyTimeoutError.