Thought leadership from the most innovative tech companies, all in one place.

How to Retry Requests Using Axios

A tutorial on using the Axios interceptor to retry requests.

image

Retry Axios request

Preface

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.

image

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:

  1. Request aborted
  2. Network error
  3. Network timeout
  4. 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 Network timeout.

Retry request while failed

image

Using interceptor to retry request

While using Axios, we can use interceptors which can intercept requests and responses before they are handled by then or 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.

image

Then we can simulate the Network Error :

image

Conclusion

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 retry and retryDelay.

That's it for this topic. Hope this helps you. Thank you for reading.




Continue Learning