Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exiting the process after uncaughtException

In my NodeJS app, whenever it encounters an unhandled exception, I want the process to exit.

However, it seems like according to NodeJS's docs, it does exit by default. So my question is - should I have something like this in my code?

    process
        .on('uncaughtException', (err) => {
            log.error('uncaughtException:', err.message);
            log.error(err.stack);
            process.exit(1);
    });

or should I leave the process.exit(1) part out of it because it's not needed?

like image 317
Gambit2007 Avatar asked Oct 26 '25 05:10

Gambit2007


1 Answers

The part process.exit(1) is needed, it does not exit by default and your application may terminate in an unexpected state so you should put process.exit(1) in uncaughtException

However, it is also a good practice to put event unhandledRejection (if you are using Promises in your app) so you better understand what has happened.

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

Moreover as a side-note(Dario mentions, and quotes official documentation here, see documentation)

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

like image 105
Irony Stack Avatar answered Oct 28 '25 17:10

Irony Stack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!