简体   繁体   中英

Prevent Node.js 8+ from exiting on uncaught exceptions

Disclaimer: I know how bad of a practice not exiting the application when it is in an undefined state is. I intend to use this only for testing and because I am wondering whether it is possible at all.

I thought by handling process uncaughtException event one could prevent Node.js 8+ from shutting down but the following script finishes after the first throw

process.on('uncaughtException', err => {
  console.log(err, 'Uncaught Exception thrown');
  // process.exit(1);
});

console.log("before throwing the first time")
throw 42;
console.log("before throwing once again")
throw 42;
console.log("after throwing a 2nd time")

How can I prevent that?

Your exception handler is doing the right thing. The reason why node is exiting is because you have no other events to process. If you had other events, the process would continue to run:

process.on('uncaughtException', err => {
  console.log(err, 'Uncaught Exception thrown');
  // process.exit(1);
});

setTimeout(function() { console.log('still running') }, 1000)
console.log("before throwing the first time")
throw 42;
console.log("before throwing once again")
throw 42;
console.log("after throwing a 2nd time")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM