Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try catch block is not catching nested callbacks

Tags:

javascript

I'm trying to understand how to use try/catch when it comes to nested callbacks. Why doesn't this piece of code catch my new error ?

function test(cb) {
  setTimeout(function() {
    throw new Error("timeout Error");
  }, 2000);
}

try {
  test(function(e) {
    console.log(e);
  });
} catch (e) {
  console.log(e);
}
like image 736
runners3431 Avatar asked Oct 21 '16 14:10

runners3431


2 Answers

The error happens asynchronously, when the function passed to setTimeout runs. By the time the error is thrown, the test function has already finished executing.

like image 59
Joe Attardi Avatar answered Oct 22 '22 09:10

Joe Attardi


There are many ways to set a timer for Javascript execution. Here's one way that uses Promise.race():

(async () => {
  try {
    await Promise.race([

      // Timer.
      new Promise((res, rej) => {
        setTimeout(() => {
          rej("Timeout error!");
        }, 2000);
      }),

      // Code being timed.
      new Promise((res, rej) => {
        // Do some stuff here.
        // If it takes longer than 2 seconds it will fail.
        res("Finished in under 2 seconds.");
      })

    ]);
  } catch (err) {
    console.log("we got an err: " + err);
  }
})();
like image 1
pjb Avatar answered Oct 22 '22 10:10

pjb