Axios - Handling Errors and Using Retry Mechanisms
Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and nodejs with the same codebase). On the server-side it uses the native node.js http module, while on the client (browser) it uses XMLHttpRequests.
What are the Scenarios Where Your Axios Requests Would Fail And How Can You Debug Them?
There are 3 cases where your axios requests could fail.
1- You make a request, and the server has received it. But the response is not a 2xx code.
If this is the case, the error.response object will have some data about the failure which you can use to diagnose the problem.
2- You make a request, but there is no response from the server.
If this is the case, this time error.request object will have the data about the failure which you can use to diagnose the problem.
3- If none of the above were the case, then you probably did something wrong with the setup of your axios request. In this case, check error.message contents to see the details.
See my “Axios Interceptors - When should you use them?” post to find a more practical way to handle axios errors using interceptors.
How Would You Retry a Failing Axios Request
Of course, we cannot leave a failed request just to disappear into the darkness, right?
That could potentially cause a lot of problems with the execution of our app if that is not handled properly, and in some cases “handling” means repeating the request to succeed.
Promises can be handled in two ways using modern JS - the async/await syntax in a try/catch block, or then/catch methods.
Below I will be demonstrating both.
One thing we should remember is not to repeat an infinite amount of numbers so we will have a parameter to set the max number of times a request should be repeated.
Here is a basic example of how you could create a util function to wrap an axios request and repeat it a certain amount of times in case it fails using async/await & try/catch.
We are using an async function to wait for the result for our axios request, and a while loop to repeat the request a limited number of times in case of failure. If our request succeeds or we reach the number of max retires before that happens, we break out of the loop.
Here is a similar implementation, this time using then/catch methods. Actually since we are using await keyword, we don’t need to use the then method in the promise chain.
And if you are crazy enough you can always write a function that retries your requests forever.