node.jserror-handlingtry-catch

How can I make the loop in try and catch to continue making requests and not crash when there is an error,


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);
}

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?


Solution

  • 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);
      }
    }