I
I
Ilya Pavlov2018-03-04 03:18:39
JavaScript
Ilya Pavlov, 2018-03-04 03:18:39

How to make normal throw instead of unhandledRejection in NodeJS?

let go = async () => {
  throw new Error('Some Error');
}
go();

The result is simply output to the console:
(node:14892) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Some Error
(node:14892) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejec
tions that are not handled will terminate the Node.js process with a non-zero exit code.

And how to make a normal throw?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
eternalSt, 2018-03-04
@eternalSt

The answer to your question is in the off documentation
. The cause of the "unhandledRejection" event is also described there.
In general, there are several solutions to this problem, for example, as suggested by Sergey and Vladlen Hellsight here in the answer.
Other options:

let go = async () => {
    throw new Error('Some Error');
  }

// можно выловить ошибку в другой async функции
  (async () => {
    try{
      await go()
    }
    catch(error){
      console.error(error); // напечатать лог
      process.exit(1); // вернуть код завершения отличный от нуля
    }
  })()

// Или повесить catch на функцию `go` , это тоже сработает
  go().catch(error => { 
      console.error(error); // напечатать лог
      process.exit(1); // вернуть код завершения отличный от нуля
  })

PS If you ask the question: "Which template is better to use?". This is where opinions differ. As for me, this is how you should always try to catch errors, if this is not possible - use process.on('unhandledRejection')

S
Sergey, 2018-03-04
@SaXXuM

process.on('unhandledRejection', function (err) {
  console.log('Caught exception: ', err);
});

let go = async () => {
  throw new Error('Inner Error')
}
go();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question