Search code examples
javascripterror-handlingtry-catch

How to catch iteration number for uncaught errors?


I have a for loop inside an async function that runs a given a function calculatingFn() that has a tendency to fail by throwing an uncaught error.

(async ()=>{
  const data=[...] // some data
  for(i=0;i<data.length;i++){
    await calculatingFn(data[i]);  // throws error sometimes
  }
})()

If the loop fails, the whole program stops executing, as I expect it to. However I want to console log the last iteration number so that I can pick off where I left it. So I thought of catching the error

(async ()=>{
  // the rest of the code
})().catch(err=>console.log(err))

Now instead of logging the error message, I wish to get the last iteration number like so

(async ()=>
  const data=[...]
  for(i=0;i<data.length;i++){
    await calculatingFn(data[i]);
  }
})().catch((err,i)=>console.log(i))  // accessing i inside the catch block

How can I access i, the iteration number, inside the catchblock. Note that the error is thrown by internal processes of the libraries I am using.


Solution

  • instead of catch error from outside of the loop catch the error inside the loop then do what you want and the loop will resumed after your statement.

    (async ()=>{
      const data=[...] // some data
      for(i=0;i<data.length;i++){
        await calculatingFn(data[i]).catch(err=>console.log(err)); 
      }
    })()