'uncaughtException' in http.createServer

I want to res.end('server error') in request if error. My code:

http.createServer(function(req,res){
  process.on('uncaughtException', function() {
    res.end('server error')
  })
  handlers(req,res)
}).listen(1337)

What's wrong with my decision?

You'll get an error/warning like this:

(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit.
Trace: 
    at EventEmitter.<anonymous> (events.js:139:15)
    at EventEmitter.<anonymous> (node.js:389:29)
    at Server.<anonymous> (/Users/taf2/work/phonetrac/services/ctm-pool/foo.js:2:11)
    at Server.emit (events.js:70:17)
    at HTTPParser.onIncoming (http.js:1572:12)
    at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:91:29)
    at Socket.ondata (http.js:1468:22)
    at TCP.onread (net.js:374:27)

I'm going to assume you are doing the above because you noticed that when you started catching uncaughtException, client connections were no longer being closed so, on an error the client connection would never be released. If for example, you were embedding the node.js endpoint as a client side request in a script tag e.g.

<script src="http://127.0.0.1:1337/yourendpoint.js"></script>

This will hang the consumer of your service... hopefully you're embedding your script using an async technique...

Anyways, to handle the error using your technique can work provided you handle releasing the event listener.

function handleError(err) {
  console.error("Caught exception:", err, err.stack);
  this.end();
  this.emit("cleanup");
}

require('http').createServer(function(req, res) {
  var errorHandler = handleError.bind(res)
  process.on("uncaughtException", errorHandler);
  res.on("cleanup", function() { process.removeListener("uncaughtException", errorHandler); });

  this.is.an.error;

  res.end();
  res.emit("cleanup");
}).listen(1337);

Trying it out we get no leaks, our errors are handled and the connections are closed leaving our clients free to move on to the next error:

ab -n 100 -c 10 http://127.0.0.1:1337/

However, this solution will break down under concurrency if your server does anything complex like the following:

function handleError(err) {
  console.error("Caught exception:", err, err.stack);
  this.end();
  this.emit("error:cleanup");
}

require('http').createServer(function(req, res) {
  var errorHandler = handleError.bind(res)
  process.on("uncaughtException", errorHandler);
  res.on("error:cleanup", function() { process.removeListener("uncaughtException", errorHandler); });

  setTimeout(function() {
    this.is.an.error;
    res.end();
    res.emit("cleanup");
  },1000);

}).listen(1337);

The problem here is uncaughtException will be fired for all errors and they will be overlapping. This means for catching a global error like this your best to only have one process.on("uncaughtException" handler.

Instead in the above situation you'll want to:

  • have an isolated try { } catch {} block - this can be difficult to get right.
  • allow the exception go uncaught and crash the process, use monit or something similar to restart the process.
  • you might try an array with a setInternval cleanup function to filter out closed connections.

The following is using setInterval.

var connectionIndex = 0;
var connections = [];

function handleError(err) {
  console.error("Caught exception:", err, err.stack);
  connections.forEach(function(conn) {
    conn.end();
  });
}

var server = require('http').createServer(function(req, res) {
  connections.push(res.connection);

  setTimeout(function() {
    this.is.an.error;
    res.end();
  },100);

});

setInterval(function() {
  console.log("conn check: %d", connections.length);
  connections = connections.filter(function(conn) {
    return !conn.destroyed;
  });
},1000);

process.on("uncaughtException", handleError);

server.listen(1337);

I kind of like the last solution, but I'm sure there might be edges to it that bite, so using the second solution have a monitoring service to restart your server is probably best.

process.on("uncaughtException", handleError);