Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restart Node.js application when uncaught exception occurs

How would I be able to restart my app when an exception occurs?

process.on('uncaughtException', function(err) {         
  // restart app here
});

1 Answers

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.

like image 125
hexacyanide Avatar answered Sep 13 '25 05:09

hexacyanide