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 
})

Leave a Reply

Your email address will not be published. Required fields are marked *

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