TiansHUo TiansHUo - 1 year ago 247
Node.js Question

How do I prevent node.js from crashing? try-catch doesn't work

From my experience, a php server would throw an exception to the log or to the server end, but node.js just simply crashes. Surrounding my code with a try-catch doesn't work either since everything is done asynchronously. I would like to know what does everyone else do in their production servers.

Answer Source

Other answers are really insane as you can read at Node's own documents at http://nodejs.org/docs/latest/api/process.html#process_event_uncaughtexception

If someone is using other stated answers read Node Docs:

Note that uncaughtException is a very crude mechanism for exception handling and may be removed in the future

So after going through I finally came up with what Node document itself suggests:

Don't use it, use domains with cluster instead. If you do use uncaughtException, restart your application after every unhandled exception!

Solution is DOMAIN with Cluster

What we actually do is send an error response to the request that triggered the error, while letting the others finish in their normal time, and stop listening for new requests in that worker.

In this way, domain usage goes hand-in-hand with the cluster module, since the master process can fork a new worker when a worker encounters an error. See the code below to understand what I mean

By using Domain, and the resilience of separating our program into multiple worker processes using Cluster, we can react more appropriately, and handle errors with much greater safety.

var cluster = require('cluster');
var PORT = +process.env.PORT || 1337;


   cluster.on('disconnect', function(worker) 
    var domain = require('domain');
    var server = require('http').createServer(function(req, res) 
        var d = domain.create();
        d.on('error', function(er) 
            //something unexpected occurred
            console.error('error', er.stack);
               //make sure we close down within 30 seconds
               var killtimer = setTimeout(function() 
               }, 30000);
               // But don't keep the process open just for that!
               //stop taking new requests.
               //Let the master know we're dead.  This will trigger a
               //'disconnect' in the cluster master, and then it will fork
               //a new worker.

               //send an error to the request that triggered the problem
               res.statusCode = 500;
               res.setHeader('content-type', 'text/plain');
               res.end('Oops, there was a problem!\n');
           catch (er2) 
              //oh well, not much we can do at this point.
              console.error('Error sending 500!', er2.stack);
    //Because req and res were created before this domain existed,
    //we need to explicitly add them.
    //Now run the handler function in the domain.
        //You'd put your fancy application logic here.
        handleRequest(req, res);

Though Domain is pending deprecation and will be removed as the new replacement comes as stated in Node's Documentation

This module is pending deprecation. Once a replacement API has been finalized, this module will be fully deprecated. Users who absolutely must have the functionality that domains provide may rely on it for the time being but should expect to have to migrate to a different solution in the future.

But until the new replacement is not introduced, Domain with Cluster is the only good solution what Node Documentation suggests.

For in-depth understanding Domain and Cluster read

https://nodejs.org/api/domain.html#domain_domain (Stability: 0 - Deprecated)


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download