Catch all uncaughtException for Node js app

You can use processuncaughtException‘ and ‘unhandledRejection‘ events.

Also remember that it is not safe to resume normal operation after ‘uncaughtException‘, because the system becomes corrupted:

The correct use of ‘uncaughtException‘ is to perform synchronous
cleanup of allocated resources (e.g. file descriptors, handles, etc)
before shutting down the process.

Example:

process
  .on('unhandledRejection', (reason, p) => {
    console.error(reason, 'Unhandled Rejection at Promise', p);
  })
  .on('uncaughtException', err => {
    console.error(err, 'Uncaught Exception thrown');
    process.exit(1);
  });

Leave a Comment