Naveen
Naveen

Reputation: 371

Nodejs uncaught exception handling

What is the prefered way of handling uncaughtexception in nodejs application?

FYI, I am having a Express based REST Api nodejs server.

Upvotes: 3

Views: 7179

Answers (2)

Vishnu Kyatannawar
Vishnu Kyatannawar

Reputation: 353

Lot of people do this

process.on('uncaughtException', function (err) {
   console.log(err);
});

This is bad. When an uncaught exception is thrown you should consider your application in an unclean state. You can’t reliably continue your program at this point.

Let your application crash, log and restart.

process.on('uncaughtException', function (err) {
  console.error((new Date).toUTCString() + ' uncaughtException:', err.message);
  console.error(err.stack);
  // Send the error log to your email
  sendMail(err);
  process.exit(1);
})

let your application crash in the event of an uncaught exception and use a tool like forever or upstart to restart it (almost) instantly. You can send an email to be aware of such events.

Upvotes: 9

ChaseMoskal
ChaseMoskal

Reputation: 7651

an exception should do one of two things:

  1. be caught and handled properly by the program
  2. cause the program to terminate in catastrophic angry failure

if you have uncaught exception that you are trying to get rid of in your program, you either have a bug to fix, or you need to catch that exception and handle it properly

complicated async code, typically involving a mess of disorganized uncaught promises, is often the cause of many uncaught exception problems -- you need to watch how you return your promise chains very carefully

the only permanent solution is to adopt modern async/await code practices to keep your async code maintainable

Upvotes: 0

Related Questions