Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch getaddrinfo ENOTFOUND

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));
    });

}
like image 567
Maxali Avatar asked Feb 09 '14 17:02

Maxali


People also ask

How do you resolve Getaddrinfo Enotfound?

The error getaddrinfo ENOTFOUND localhost is caused by Webpack cannot found localhost address. To solve it, open the terminal: sudo nano /etc/hosts. Add following into the hosts file and save it.

What does error Getaddrinfo Enotfound mean?

If you try to run your JSON server and see this error message “getaddrinfo ENOTFOUND localhost,” it's happening because Webpack cannot find your localhost address.


1 Answers

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' }
like image 96
Paul Mougel Avatar answered Oct 05 '22 15:10

Paul Mougel