1

function abc() {
  try {
    setTimeout(() => {
      console.log('inside timeout!!');
      throw new Error('Somehting went wrong!!');
    }, 1000);
  } catch (err) {
    console.log('Gonna catch it here and throw is again', err);
    throw new Error(err);
  }
}
try {
  abc();
} catch (err) {
  console.log('err caught here', err);
}

How to catch the error ? Where should I wrap my code with try/catch ? Even with promise why catch block didn't catch the error.

async function abc() {
   setTimeout(() => {
     throw new Error();
   }, 1000);
}

try {
  abc();
} catch (err) {
  console.log('err is ', err);
}
john33
  • 61
  • 2
  • 8
  • You have to wrap the inside of the callback, since `setTimeout(() => {throw new Error();}, 1000);` is a successful call. The error doesn’t come until later. – Sebastian Simon Jan 14 '19 at 17:58
  • You should reject the promise in order for catch function to execute. This catch function is different from the `try catch` construct to catch exceptions – Abhishek Mehandiratta Jan 14 '19 at 18:03
  • @Xufox, that means no way to catch errors of any callback function outside of the callback function ? – john33 Jan 14 '19 at 18:07

1 Answers1

4

Wrap it into a Promise:

function abc(simulateError) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (simulateError)
        reject('Something went wrong')
      else
        resolve('foo')
    })
  })
}

// Call it using then/catch to handle result or errors...
abc(true).then(result => {
  console.log(result)
})
.catch(err => {
  console.log(err)
})

// or await on the Promise, which allows using try/catch.
;(async () => {
  try {
    const result = await abc(true)
    console.log(result)
  } catch (err) {
    console.log(err)
  }
})()
nicholaswmin
  • 21,686
  • 15
  • 91
  • 167
  • Any other suggestion instead of .catch block with promise. – john33 Jan 14 '19 at 18:02
  • Yes, [error-first callbacks](http://fredkschott.com/post/2014/03/understanding-error-first-callbacks-in-node-js/) but that's an outdated practice. – nicholaswmin Jan 14 '19 at 18:03
  • What's the difference between .catch of promise block and normal catch block – john33 Jan 14 '19 at 18:03
  • `try/catch` won't help you here, even if it's within an `async` function. The only way to handle errors from `setTimeout` is either by passing a callback or Promises. – nicholaswmin Jan 14 '19 at 18:05
  • With Async and await, have to await just for the catch block only, isn't it the limitation of normal catch block ? – john33 Jan 14 '19 at 18:15
  • `try/catch` won't work properly for asynchronous code unless you're `await`ing something inside the `try` block. – nicholaswmin Jan 14 '19 at 18:17
  • ` async function abc() { try { await setTimeout(() => { console.log('inside timeout!!'); throw new Error('Somehting went wrong!!'); }, 1000); } catch (err) { console.log('Gonna catch it here and throw is again', err); throw new Error(err); } } (async () => { try { await abc(); console.log('after timeout'); } catch (err) { console.log('err caught here', err); } })();` – john33 Jan 14 '19 at 18:18
  • Not sure I can help you, the code you posted indicates you don't really undestand how asynchronous code works to begin with. For one, setTimeout doesn't return a `Promise` so you can't await it. Also throwing errors from within `setTimeout` won't help you in any case, either `async` or non-`async` functions. `setTimeout` uses a *callback* to propagate it's result. You can either wrap it into a `Promise` and use `reject` or use callbacks to propagate the error. Throwing errors won't work (unless you overwrite `setTimeout` as an `async` function and use it as such but that's another story). – nicholaswmin Jan 14 '19 at 18:26
  • Thank you so much! One more things, by passing async function to setTimeout function, how can i await it? – john33 Jan 14 '19 at 18:32
  • You cannot `await setTimeout` because `setTimeout` does not return a `Promise`. – nicholaswmin Jan 14 '19 at 18:49
  • So it does not make any sense to pass async function as a first argument of the setTimeout Function, as you mentioned no way to await it. Plz correct it if i am wrong. – john33 Jan 14 '19 at 19:01
  • You are correct – nicholaswmin Jan 14 '19 at 19:08