2014-02-09 23 views
7

我有一個鏈接列表,我需要在處理一些數據之前檢查。使用http.get檢查標題返回錯誤:如何捕獲getaddrinfo ENOTFOUND

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

我無法處理此錯誤,並退出該過程。我嘗試res.on(「錯誤」)並嘗試http.get上捕獲,但沒有任何工作。

下面的代碼片段,並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)); 
    }); 

} 
+1

退房[域](http://nodejs.org/api/domain的.html)。 – Jason

回答

19

你只需要處理error事件,如錯誤消息指出。根據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.

下面是一個使用例如:

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

其產生:

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

可以告訴我的解決方案也 –

+0

只是補充說,這種技術也適用於NPM'request'模塊。 – maxko87

+0

這會允許其他代碼運行嗎? – Tomas