1 simple trick to prevent your node.js server from crashing on production

Santiago Quinteros - CEO & CTO - Software on the road
Santiago Quinteros

Have you ever hear about the "uncaughtException" ?

The "uncaughtException" event is emitted when an uncaught JavaScript exception bubbles all the way back to the event loop.

process.on('uncaughtException', (error)  => {
    console.log('Oh my god, something terrible happened: ',  error);

    process.exit(1); // exit application 


We must shutdown our application after handle the error because is not safe to resume normal operation after "uncaughtException" the system becomes corrupted.

But wait! There is more

The "unhandledRejection" event is emitted whenever a Promise is rejected and no error handler is attached to the promise within a turn of the event loop. When programming with Promises, exceptions are encapsulated as "rejected promises". Rejections can be caught and handled using promise.catch() and are propagated through a Promise chain. The "unhandledRejection" event is useful for detecting and keeping track of promises that were rejected whose rejections have not yet been handled.

process.on('unhandledRejection', (error, promise) => {
  console.log(' Oh Lord! We forgot to handle a promise rejection here: ', promise);
  console.log(' The error was: ', error );

I suggest you to add this handlers at the beginning of the entry point of your application.

Happy coding!!

Get the latest articles in your inbox.

Join the other 2000+ savvy node.js developers who get article updates. You will receive only high-quality articles about Node.js, Cloud Computing and Javascript front-end frameworks.


CEO at Softwareontheroad.com