4

I am trying to catch an error caused by an async javascript callback function,

try{
  setTimeout(()=>{ 
    throw err 
    console.log("after throw") 
  }, 1000)
}catch(e){
  console.log("caught");
}

But as many of you may know catch block is never executed, so what exactly is happening here?

I know I can achieve similar thing using promises and async/await,

async foo(){
  try{
    await setTimeoutPromise(1000);
  }catch(e){
    alert("caught");
  }
}
FZs
  • 16,581
  • 13
  • 41
  • 50
laxman
  • 1,781
  • 4
  • 14
  • 32
  • or [Error-handling try & catch + callback?](https://stackoverflow.com/questions/12203224/error-handling-try-catch-callback) – AZ_ Aug 29 '19 at 05:59
  • 1
    It's not quite the same. The scope of this question is more about the reason, not the workaround. – Holli Aug 29 '19 at 06:03
  • 1
    but the answers do include the reason, duplicate does not mean mirror images. – AZ_ Aug 29 '19 at 06:04
  • [Don't throw exceptions in asynchronous callbacks](https://stackoverflow.com/a/25144936/1048572). Throw them in promise callbacks instead. – Bergi Aug 29 '19 at 08:15

2 Answers2

1

When you use setTimeout, the callback gets pushed into the event loop (moved out of the JS Engine and into the realm of the runtime/browser) and your foo function exits immedeatly.

After the timeout AND once the stack is empty, the event loop will put the callback onto the stack and run it. That's why the try/catch and the callback are independent of each other. That's also why setTimeout(1000) does not mean in a second but not earlier than and somewhat close to one second.

See What the heck is the event loop anyway? | Philip Roberts | JSConf EU

Holli
  • 5,072
  • 10
  • 27
1

These are two different things.

The first code won't catch the error, since it happens asynchronously, and try...catch will only catch synchronously thrown exceptions.

The second code will catch the error, because await 'synchronize' the code (makes it look and work like it would've been synchronous), and the error thrown only by await: if you haven't been used it, you would get only a rejected promise (You can't really throw anything from an async function!)

To make the first code working, move the try...catch inside the callback:

setTimeout(()=>{ 
  try{
    throw err
  }catch(e){
    console.log('catched')
  }
  console.log("after throw") 
}, 1000)
FZs
  • 16,581
  • 13
  • 41
  • 50
  • 1
    I don't think it's accurate to say that `async/await` "synchronize" the code. It remains asynchronous, just easier to understand and deal with. – lonesomeday Aug 29 '19 at 13:51
  • 1
    @lonesomeday Yes, I know, that's why I quoted the word 'synchronize'. I haven't found the accurate way to express what I would like to say... Now I've rephrased it, so it might be clearer. – FZs Aug 29 '19 at 18:08