Reputation: 3958
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?
Upvotes: 4
Views: 2613
Reputation: 3088
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 Promise
s 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.
Upvotes: 6