node.js: Handling refused http client connections

If your node.js process is unexpectedly terminating, spitting out something like this:

events:11
        throw arguments[1];
                       ^
Error: ECONNREFUSED, Connection refused
    at IOWatcher.callback (net:756:22)
    at node.js:204:9

then chances are you’re using http.Client and the host+port you’re trying to connect to is offline or otherwise unreachable.

Unfortunately node by default just spits out this cryptic message and then terminates the entire process upon any such connection failure.

Fortunately adding a little support code can make handling such occurrences more tolerable:

var sys = require('sys'),
    http = require('http');

var connection = http.createClient(9090, 'localhost'),
    request = connection.request('/');

request.socket.addListener('error', function(socketException){
    if (socketException.errno === 61 /*ECONNREFUSED*/) {
        sys.log('ECONNREFUSED: connection refused to '
            +request.socket.host
            +':'
            +request.socket.port);
    } else {
        sys.log(socketException);
    }
});

request.addListener('response', function(response){
    var data = '';

    response.addListener('data', function(chunk){ 
        data += chunk; 
    });
    response.addListener('end', function(){
        // Do something with data.
    });
});

request.end();

The gotcha here is placing the error event listener on the request’s socket — it won’t get fired if attached to the request itself, and you’ll still just exit on failed connection attempts.

Update: Ryan Dahl tweets:

the http connection object === req.socket. Also process.ECONNREFUSED (ugly)

Thanks, Ryan. Based on your feedback, here’s some updated sample code:

var sys = require('sys'),
    http = require('http');

var connection = http.createClient(9090, 'localhost'),
    request = connection.request('/');

connection.addListener('error', function(connectionException){
    if (connectionException.errno === process.ECONNREFUSED) {
        sys.log('ECONNREFUSED: connection refused to '
            +connection.host
            +':'
            +connection.port);
    } else {
        sys.log(connectionException);
    }
});

request.addListener('response', function(response){
    var data = '';

    response.addListener('data', function(chunk){ 
        data += chunk; 
    });
    response.addListener('end', function(){
        // Do something with data.
    });
});

request.end();

node.js Jun 4 2010