how to catch error inside closure/ifffy functions without promise in javascript

Viewed 81

how to catch error inside closure/ifffy functions in outter try catch without using promise in javascript

//closures

function abc(a,b){
    try{
        setTimeout(()=>{
            throw new Error("error")
        },0)
    }catch(e){
        console.log(e)
    }
}
abc(10,0)

//iify functions

(function abc(a,b){
    try{
        setTimeout(()=>{
            throw new Error("error")
        },0)
    }catch(e){
        console.log(e)
    }
})(10,0)

1 Answers

In your case, the error was thrown from the setTimeout that wasn't surrounded by try and catch, and executed after your function has completed, this should work:

(function abc(a,b){
    const catchIfNeeded = (f) => () => {
      try{
        f()
      }catch(e){
        console.log(e)
      }
    }
    setTimeout(catchIfNeeded(() => {
      throw new Error("error")
    }),0)

})(10,0)

Related