Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Restart Node.js application when uncaught exception occurs

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.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Restart Node.js application when uncaught exception occurs

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×