Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch node.js http error on nonexistent host?

when I'm trying to use the http module to access nonexistent host, like this:

requestToRemote = http.createClient(80, 'fjasdfhasdkfj.vvvxcz').request(
    method,
    path,
    headers
);

But I get the following error:

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: getaddrinfo ENOENT
    at errnoException (dns.js:31:11)
    at Object.onanswer [as oncomplete] (dns.js:140:16)

I'd like to catch this error, so I've tried try/catch and setting the error listeners of a bunch of request properties, but none of if worked. How can I catch the error?

like image 353
Fluffy Avatar asked Dec 28 '11 13:12

Fluffy


People also ask

How does node js handle HTTP request?

The http module is available natively with Node. js; there is no additional installation required. The data is initially converted into a string using the stringify function. The HTTP options specify the headers, destination address, and request method type.

What is stack trace in node JS?

The stack trace is useful while debugging code as it shows the exact point that has caused an error. Errors in Node. js can be classified into four broad categories: Standard JavaScript Errors.


1 Answers

Looks like the error is thrown from http.Client, not the request. How about something like:

var site = http.createClient(80, host);
site.on('error', function(err) {
    sys.debug('unable to connect to ' + host);
});
var requestToRemote = site.request(...);

FYI, http.createClient has been deprecated -- the following should work using the get convenience method:

http.get({host: host}, function(res) {
    ...
}).on('error', function(e) {
    console.log("Got error: " + e.message);
});
like image 66
mike Avatar answered Oct 06 '22 23:10

mike