Home > front end >  How can I make the loop in try and catch to continue making requests and not crash when there is an
How can I make the loop in try and catch to continue making requests and not crash when there is an

Time:08-21

let array = [];

try {
    for (let i = 0; i < postcodes.length; i  ) {

      const companyHouseData = await axios.get(`https://api.company-information.service.gov.uk/advanced-search/companies?location=${postcodes[i}`,{auth});

      if (companyHouseData.status) {
        array.push(companyHouseData)
      }

    }
}catch{
    console.log(err);
}

Hi there, I am making a requests in the for loop and pushing each response to an array.

The problem I have here is that when there is a bad request (404 status code). My loop breaks and the error is catch.

How can I make the loop to continue making requests and not crash when there is a status code 404.

CodePudding user response:

I suggest to put the try catch inside the for loop for every request, this way if one request fails it will get caught and you can do some additional error handling and the rest of the loop will continue.

CodePudding user response:

If you want to continue to make requests with axios, you should try/catch the axios call, not the whole for loop.

The code should look something like this:

let array = [];

for (let i = 0; i < postcodes.length; i  ) {

  try {
    const companyHouseData = await axios.get(`https://api.company-information.service.gov.uk/advanced-search/companies?location=${postcodes[i]}`,{auth});
    if (companyHouseData.status) {
      array.push(companyHouseData)
    }
  } catch (error) {
    console.error(error);
  }
}
  • Related