26

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
  • 641
  • 3
  • 7
  • 17

2 Answers2

40

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;
        });
}
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
4

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

Paul
  • 141
  • 2
  • 8