Restart Node.js application when uncaught exception occurs
Problem
How would I be able to restart my app when an exception occurs?
process.on('uncaughtException', function(err) {
// restart app here
});
Problem courtesy of: Jeff
Solution
You could run the process as a fork of another process, so you can fork it if it dies. You would use the native Cluster module for this:
var cluster = require('cluster');
if (cluster.isMaster) {
cluster.fork();
cluster.on('exit', function(worker, code, signal) {
cluster.fork();
});
}
if (cluster.isWorker) {
// put your code here
}
This code spawns one worker process, and if an error is thrown in the worker process, it will close, and the exit will respawn another worker process.
Solution courtesy of: hexacyanide
Discussion
View additional discussion.