2

When a promise throws an error and we have to catch it just so it won't show "Uncaught dummy error", I found those similar approaches:

Using Promise.then: const promise1 = new Promise((resolve, reject) => {throw 'dummy error'}).then(null, error => console.error(error));

Using Promise.catch: const promise2 = new Promise((resolve, reject) => {throw 'dummy error'}).catch(error => console.error(error));

What should be the best practice to follow in this scenario?

When tested, both approaches are returning 'dummy error' in console.

  • 3
    `.catch()` [calls `.then()` under the hood](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch#description). It is just syntactic sugar over `.then(null /* undefined */, () => {})`. – InSync Jul 17 '23 at 12:03
  • This is not opinion-based, there's clear and obvious differences. – Evert Jul 17 '23 at 18:06
  • @Evert There are no differences? – Bergi Jul 17 '23 at 19:26
  • @Bergi only if you remove all context. The answer from rveerd is a great example, plus legibility. – Evert Jul 17 '23 at 21:08
  • @Evert The question is asking about the difference between `then(null, …)` and `.catch(…)` (which is none), not about [the difference between `.then(…, …)` and `.then(…).catch(…)`](https://stackoverflow.com/q/24662289/1048572). – Bergi Jul 17 '23 at 21:21
  • @Bergi 100% agree they are functionally identical. I guess I'm arguing one of those is better in terms of how people will interpret it and potentially introduce bugs. I believe that difference is not opinion-based. – Evert Jul 18 '23 at 06:32
  • @Evert Ah, yes, totally agree. I had voted to reopen as well – Bergi Jul 18 '23 at 08:31

1 Answers1

-1

They are not the same when the result callback (the first argument to then()) throws an error itself.

Promise.resolve('done')
  .then(
    () => { throw new Error('doh!')},
    (err) =>  console.error('I cannot catch the error thrown in .then', err)
  );

Promise.resolve('done')
  .then(() => { throw new Error('doh!')})
  .catch((err) => console.error('I can catch the error thrown in .then', err));

Because of this I prefer the second form. But you should use async/await if possible.

rveerd
  • 3,620
  • 1
  • 14
  • 30
  • That is not what OP is doing. (If they were, it would be a duplicate of the canonical [When is `.then(success, fail)` considered an antipattern for promises?](https://stackoverflow.com/q/24662289/1048572)) – Bergi Jul 17 '23 at 19:25