Skip to content

Prevent your node.js server from crashing on production

This tiny piece of code will handle all uncaught exceptions and just log it to the console.

The โ€œuncaughtExceptionโ€ event is emitted when an uncaught JavaScript exception bubbles all the way back to the event loop. It’s recommended we must shutdown our application after handle the uncaughtException.

Advertisements
process.on('uncaughtException', (error)  => {
   console.log('Alert! ERROR : ',  error);
   process.exit(1); // Exit your app 
})

Similar to uncaughtException, we should also handle unhandledRejection, emitted whenever aย Promiseย is rejected and no error handler is attached to the promise within a turn of the event loop.

Advertisements
process.on('unhandledRejection', (error, promise)  => {
   console.log('Alert! ERROR : ',  error);
   process.exit(1); // Exit your app 
})
See also  How to uninstall npm modules in node.js?

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.