Question

I have a list of links that I need to check before processing some data. Checking headers with http.get returns error:

events.js:72   
        throw er; // Unhandled 'error' event    
          ^    
Error: getaddrinfo ENOTFOUND       
    at errnoException (dns.js:37:11) 

I cannot handle this error, and exits the process. I tried res.on("error") and try..catch on http.get but nothing works.

Below is the code snippet, and here is live example at runnable.com

//This is OK
getHeaders('http://google.com/404pag-that-does-not-exit');


//Here is the error.
//Uncoughtable error!
getHeaders('http://doesnotexistooooo.com');

function getHeaders(link){
    var _http = require("http");
    var myUrl = require("url");

    var qs=(myUrl.parse(link).search==null) ? "" : myUrl.parse(link).search ;
    var path=myUrl.parse(link).pathname;

    var options = {
        hostname: myUrl.parse(link).hostname,
        path: path+qs,
        method: 'HEAD'
    };
    _http.get(options, function(res) {
        res.on('error',function(e){
            console.log("Error: " + myUrl.parse(link).hostname + "\n" + e.message); 
            console.log( e.stack );
        });
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
    });

}
Was it helpful?

Solution

You just need to handle the error event, as stated in the error message. According to the documentation:

If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP parse errors) an 'error' event is emitted on the returned request object.

Here is a usage example:

var getRequest = _http.get(options, function(res) {
    // …
});
getRequest.on('error', function (err) {
    console.log(err);
});

which yields:

$ node test.js
{ [Error: getaddrinfo ENOTFOUND] code: 'ENOTFOUND', errno: 'ENOTFOUND', syscall: 'getaddrinfo' }

OTHER TIPS

At the very top level, you can do

process.on('uncaughtException', function(err) {
  console.log('### BIG ONE (%s)', err);
});

if you using request npm

request
  .get('http://example.com/doodle.png')
  .on('response', function(response) {
    console.log(response.statusCode) // 200
    console.log(response.headers['content-type']) // 'image/png'
  })
  .on('error', function(err) {   // <------- add this 
    console.log(err)
  });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top