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 an error:

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

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

Below is a snippet of code, but here is a live example on 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)); }); } 
+11
dns getaddrinfo
source share
3 answers

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

If any error occurs during the request (be it with DNS resolution, TCP-level errors, or actual HTTP parsing errors), the error event is emitted to 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 gives:

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

At the highest level you can do

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

if you use npm request

 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) }); 
0
source share

All Articles