www.joinplank.com
Open in
urlscan Pro
63.35.51.142
Public Scan
URL:
https://www.joinplank.com/articles/axios-handling-errors-and-using-retry-mechanisms
Submission: On August 16 via api from US — Scanned from DE
Submission: On August 16 via api from US — Scanned from DE
Form analysis
0 forms found in the DOMText Content
Labs All Labs Product Web3 Machine Learning showcase articles fellowship join a team Work with a team Labs All Labs Product Web3 Machine Learning Showcase Working with us articles Careers fellowship Contact Us Build a team Join a team Back to Articles AXIOS - HANDLING ERRORS AND USING RETRY MECHANISMS Technical Machine Learning 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. axios.get('/some/resource) .then(function (response) { // Request was successful }) .catch(function (error) { if (error.response) { // Case 1 console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // Case 2 console.log(error.request); } else { // Case 3 console.log('Error',error.message); } // Use the toJson() method to get more info about the problem. console.log(error.toJSON()) console.log(error.config); }); Copy 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. import axios from 'axios'; export const retryGetRequest = async (url, maxRetries) => { let response = null let retries = 0; let success = false; while (retries <= maxRetries && !success) { try { response = await axios.get(url); success = true console.log("Axios SUCCESS") break; } catch (error) { console.log(error.toJSON()) } retries++ } if(retries >= maxRetries) console.log(`Too many request retries.`); return response; } Copy 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. import axios from 'axios'; export const retryGetRequest = async (url, maxRetries, retries = 0) => { let result:any = null if(retries < maxRetries){ result = await axios.get(url) .catch(error => { retries++ retryGetRequest(url, maxRetries, retries) console.log("Retry number: " + retries) }); } if(retries >= maxRetries) console.log(`Too many request retries.`); return result; } Copy And if you are crazy enough you can always write a function that retries your requests forever. const infiniteRetires = async (url) => { while (true) { try { let result = await axios.get(url) // returning a result will break out of the loop here return result; } catch (error) { console.log("Trying again...") } } } Copy AUTHORS SERDAR ONUR Product FURTHER READING view all Technical Code assistant Typescript software development Productivity tools INTELLIGENT AUTOCOMPLETE BUILT INTO PROJECT USING GITHUB COPILOT Technical chatGPT software development Productivity tools SIX STEPS TO LEARN ABOUT A SPECIFIC APIS/LIBRARIES AND FRAMEWORKS WITH CHATGPT Technical chatGPT software development Productivity tools SAVE TIME GENERATING CODE WITH CHATGPT Technical chatGPT Programming Productivity tools EVERYTHING YOU CAN DO WITH A CODE SNIPPET IN CHATGPT Technical chatGPT dev environment software development Productivity tools CONFIGURING THE ENTIRE DEVELOPMENT ENVIRONMENT WITH CHAT GPT Insight software development LLM-powered AI-powered Productivity tools MAXIMIZING YOUR POTENTIAL AS A PROGRAMMER WITH AI ASSISTANCE Insight AXIOS INTERCEPTORS - WHEN SHOULD YOU USE THEM? Our Company Fellowship Work with a team About us Join a Team Our Labs Product Web3 Machine Learning Our Work Articles Showcase Get in touch Contact Us C2023 IDYIA, LLC. All Rights Reserved. Cookies Privacy Cookies Privacy Machine Learning Machine Learning