Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

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((newDate).toUTCString() + ' uncaughtException:', err.message);
  console.error(err.stack);
  // Send the error log to your emailsendMail(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.

Solution 2:

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

Post a Comment for "Nodejs Uncaught Exception Handling"