0

I want to handle the error from top catch, here is the below code.

try{
  init().catch(e=> {
    console.log('inside catch - ', e.message)
    throw e;
  })
} catch(e){
    console.log('main catch - ', e.message)
}

async function init(){
        null.split(',')
}

it logs console.log('inside catch - ', e.message) and I throw the error again so it can go to the next error handler that is console.log('main catch - ', e.message) but it is not going, Please tell me how can we do this.

AMit SiNgh
  • 325
  • 4
  • 17

2 Answers2

1

The problem you have is that when you throw e you're throwing within a callback thats executing outside of the try/catch scope.

Errors thrown asynchronously will not be handled by try/catch unless you're inside an async function. However async is simply syntactic sugar for promises.

We can refactor your code to catch again, which will have the desired result.

init().catch(e=> {
    console.log('inside catch - ', e.message)
    throw e;
}).catch(e => {
    console.log('main catch - ', e.message)
});

async function init(){
        null.split(',')
}

You can also refactor to async/await which has the same result

(async () => {
   try {
      await init().catch(e=> {
         console.log('inside catch - ', e.message)
         throw e;
      });
   } catch(e) {
      // as this function is async, this is effectively the same as adding a
      // .catch onto the promise above
      console.log('main catch - ', e.message)
   }
})();
Joey Ciechanowicz
  • 3,345
  • 3
  • 24
  • 48
0

here is improvise version of your code. what you forget is

  1. await in try.

async function a() {
  try{
    await init().catch(e => {
       console.log('inside catch - ', e.message)
      throw e;
    })
  } catch(e){
      console.log('main catch - ', e.message)
  }
}

async function init(){
  null.split(',')
}

a();
Mohit Sharma
  • 622
  • 6
  • 11