Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching ECONNREFUSED in node.js with http.request?

Tags:

node.js

I'm trying to catch ECONNREFUSED errors when using a HTTP client in node.js. I'm making requests like this:

var http = require('http');
var options = { host: 'localhost', port: '3301', path: '/', method: 'GET' };

http.request(options).on('response', function (res) {
  // do some stuff
});

I can't figure out how to catch this error:

Error: connect ECONNREFUSED
  at errnoException (net.js:614:11)
  at Object.afterConnect [as oncomplete] (net.js:605:18)

If I do request.on('error', function () {});, it doesn't catch it. If I do it like this:

var req = request.on(etc)
req.on('error', function blah () {});

Then I get TypeError: Object false has no method 'on'.

Do I really have to do a top-level uncaught error thing to deal with this? At the moment whatever I do my whole process quits out.

Edit: I found some blog posts on how to do it by creating a connection object, calling request on that, and then binding to errors on the connection object, but doesn't that make the entire http.request() shortcut useless?

like image 503
Cera Avatar asked Dec 05 '11 04:12

Cera


People also ask

What is Econnrefused Nodejs?

ECONNREFUSED error means that connection could not be made with the target service (in your case localhost:8080 ). Check your service running on port 8080. To know more about node. js errors, refer this doc.


3 Answers

Any reason you're not using http://nodejs.org/docs/v0.6.5/api/http.html#http.request as your base? Try this:

var req = http.request(options, function(res) {   // Bind 'data', 'end' events here });  req.on('error', function(error) {   // Error handling here });  req.end(); 
like image 191
Ryan Olds Avatar answered Sep 17 '22 19:09

Ryan Olds


Each call to http.request() returns its self. So try it like this...

http.request(options.function(){}).on('error',function(){}).end();
like image 44
deezgz Avatar answered Sep 16 '22 19:09

deezgz


I've got a solution for this, having tried all the suggestions on this (and many other) pages.

My client needs to detect a turnkey product that runs embedded windows. The client is served from a different machine to the turnkey.

The turnkey can be in 3 states:

  1. turned off
  2. booted into windows, but not running the turnkey app
  3. running the turnkey app

My client sends a 'find the turnkey product' GET message to my nodejs/express service, which then tries to find the turnkey product via http.request. The behavior for each of the 3 use cases are;

  1. timeout
  2. ECONNREFUSED - because the windows embedded phase of the turnkey is refusing connections.
  3. normal response to request (happy day scenario)

The code below handles all 3 scenarios. The trick to catching the ECONNREFUSED event was learning that its handler binds to the socket event.

var http = require('http');
var express = require('express');
var url = require('url');


function find (req, res) {
    var queryObj = url.parse(req.url, true).query;

    var options = {
        host: queryObj.ip, // client attaches ip address of turnkey to url.
        port: 1234,
        path: '/some/path',
    }; // http get options

    var badNews = function (e) {
        console.log (e.name + ' error: ', e.message);
        res.send({'ok': false, 'msg': e.message});
    }; // sends failure messages to log and client  

    // instantiate http request object and fire it
    var msg = http.request(options, function (response) {
        var body = '';

        response.on ('data', function(d) {
            body += d;
        }); // accumulate response chunks  

        response.on ('end', function () {
            res.send({'ok': true, 'msg': body});
            console.log('sent ok');
        }); // done receiving, send reply to client

        response.on('error', function (e) {
            badNews(e);
        }); // uh oh, send bad news to client   
    });

    msg.on('socket', function(socket) { 
        socket.setTimeout(2000, function () {   // set short timeout so discovery fails fast
            var e = new Error ('Timeout connecting to ' + queryObj.ip));
            e.name = 'Timeout';
            badNews(e);
            msg.abort();    // kill socket
        });
        socket.on('error', function (err) { // this catches ECONNREFUSED events
            badNews(err);
            msg.abort();    // kill socket
        });
    }); // handle connection events and errors

    msg.on('error', function (e) {  // happens when we abort
        console.log(e);
    });

    msg.end();
}
like image 27
VorpalSword Avatar answered Sep 19 '22 19:09

VorpalSword