3

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Gambit2007
  • 3,260
  • 13
  • 46
  • 86
  • No, if you add this handler then you must end it with `process.exit(1)`, otherwise your process will not terminate (as you want it to). – goodvibration Oct 28 '19 at 14:12
  • BTW, your entire question - you can simply try it out and see what happens. – goodvibration Oct 28 '19 at 14:13
  • Oh, so by default NodeJS exits, but if i add this custom handler it overrides the default behavior and so i have to explicitly exit? – Gambit2007 Oct 28 '19 at 14:16
  • Exactly. And like I said, you could easily try it (add a deliberate exception somewhere i your process, and see what happens when you omit the `exit` statement. – goodvibration Oct 28 '19 at 14:17
  • Yeah that's true.. thanks for the clarification! You can post this as an answer if you want and i'll accept it! – Gambit2007 Oct 28 '19 at 14:17

1 Answers1

4

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.

Shankar
  • 2,890
  • 3
  • 25
  • 40