Retry Axios request
When the user accesses our web app, the HTTP request may fail due to unstable networks, such as timeout or network exception. In this case, there will usually be an exception page to inform the user that they can re-enter the web app later. If we retry these failed HTTP requests, the user may not need to exit and re-enter our web app, the experience will be better.
We will first learn about all the exceptions that may occur if Axios requests fail, then use the interceptor of Axios to retry the HTTP request.
Exceptions of Axios request
If you have observed the exception of Axios, you can find that the name of all exceptions is
AxiosError. Axios custom handling exception
AxiosError class which inherit from
Error. So we can find all exceptions by searching the source code for AxiosError.
You may search for more than 20 places where it is used, but we only need to pay attention to the exception during the request.
The main exceptions is:
- Request aborted
- Network error
- Network timeout
- Unsupported protocol
The exception of
Request aborted maybe caused by the user canceling the request, we might not retry the request. And the exception of
Unsupported protocol don’t need to retry for it will be failed again. So we can retry the request while the request failed for
Network error or
Retry request while failed
Using interceptor to retry request
While using Axios, we can use interceptors which can intercept requests and responses before they are handled by
catch. The interceptor accepts two parameters, fulfilled callback and rejected callback. When a request failed, it will execute the rejected callback.
I created a demo on copen.io, for testing the feature, we can block the request URL with Devtools.
Then we can simulate the
Network Error :
By using the interceptor of Axios to intercept the response, if a
Network timeout or
Network error occurs, try to send the request again. We can control the number of retrying requests and the interval between each request by setting
That's it for this topic. Hope this helps you. Thank you for reading.