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));
});
}
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.
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.
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' }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With