Search code examples
javascriptnode.jsexceptionpromisetry-catch

javascript exception handling with top catch block


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.


Solution

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