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
});

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.

You have a couple of options..

  1. Restart the application using monitor like nodemon/forever
process.on('uncaughtException', function (err) {       
    console.log(err);
    //Send some notification about the error  
    process.exit(1);
});

start your application using

nodemon ./server.js 
forever server.js start
  1. Restart using the cluster

This method involves a cluster of process, where the master process restarts any child process if they killed

var cluster = require('cluster');
if (cluster.isMaster) {
   var i = 0;
   for (i; i< 4; i++){
     cluster.fork();
   }
   //if the worker dies, restart it.
   cluster.on('exit', function(worker){
      console.log('Worker ' + worker.id + ' died..');
      cluster.fork();
   });
}
else{
   var express = require('express');
   var app = express();

   .
   .
   app.use(app.router);
   app.listen(8000);

   process.on('uncaughtException', function(){
      console.log(err);
      //Send some notification about the error  
      process.exit(1);
  }
}

checkout nodemon and forever. I use nodemon for development and forever for production. Works like a charm. just start your app with nodemon app.js.


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Setting the HTML 'for' attribute in JavaScript

Similar Posts