0
votes

Is there a way to check if any given address would result in getaddrinfo error when request is made? I have list of URLs and some of them causes getaddrinfo error and crashs Node.js app. So I would like to check if an address can be resolved before I call request method. I have been trying to catch that error inside callback function of request without any luck. Thanks!

This is my attempt - ref = this;

var options = {
    host: ref.host,
    headers: {
        'user-agent': 'Mozilla/5.0'      
    },
    path: ref.pathname,
    method: "GET",
    timeout: 5000,
    followRedirect: true,
    maxRedirects: 5
};  

// Process the file.
var file = fs.createWriteStream(path.normalize(ref.saveTo + ref.name + ref.extension));

var req = ref.protocol.get(options, function(res) {        
    res.on('data', function(data) {      
        f.write(data);
    }).on('end', function() {
        f.end();
    });
});

req.on('response', function(err) {
  if(err.statusCode == '404') { 
    console.log("Response ", err);
  }
}); 

req.on('error', function(err) {
  console.log("This is error ----" + err);
});
req.end();

Edit : This is the error I get from Node.js -

Error: getaddrinfo ENOTFOUND at errnoException (dns.js:37:11) at Object.onanswer [as oncomplete] (dns.js:124:16)

1

1 Answers

0
votes

You can catch the error event on a HTTP request. For example:

var doGETRequest = require("http").get;
var req = doGETRequest("http://foo.bar", function(res) {  });
req.on("error", function errorHandler(err) {
    if(err.code === "ENOTFOUND") {
        console.log("Address not found.", e);
    } else {
        console.log("Some other error:", e);
    }
});

The reason why an event is used and not an exception is because the hostname lookup is asynchronous. Not sure why they don't just pass it as the first parameter to the callback, but that's just the way things are.