How to catch iteration number for uncaught errors?

Viewed 23

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.

2 Answers

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

Since it's an async function you can add a try ... catch block around the function call, then log the iteration and error at the same time.

I'd suggest you throw this again if you wish your top level to be able to see it.

function calculatingFn(input) {
    // Throw if our input is three...
    return input === 3 ? Promise.reject('Failure'): Promise.resolve('Success');
}

(async () => {
  const data = [1,2,3,4,5];
  for(i = 0; i < data.length; i++){
    try {
      await calculatingFn(data[i]);
    } catch (error) {
      console.log(`An error occurred at iteration #${i + 1}:`, error);
      throw new Error(`An error occurred at iteration #${i + 1}: ` + error.toString())
    }
  }
})().catch (err => console.log('Top level handler:', err.message));
.as-console-wrapper { max-height: 100% !important; }

Related