2011-12-28 23 views
11

當我嘗試使用http模塊訪問不存在的主機,像這樣:如何在不存在的主機上捕獲node.js http錯誤?

requestToRemote = http.createClient(80, 'fjasdfhasdkfj.vvvxcz').request(
    method, 
    path, 
    headers 
); 

,但我得到了以下錯誤:

node.js:201 
     throw e; // process.nextTick error, or 'error' event on first tick 
      ^
Error: getaddrinfo ENOENT 
    at errnoException (dns.js:31:11) 
    at Object.onanswer [as oncomplete] (dns.js:140:16) 

我想抓住這個錯誤,所以我嘗試了try/catch並設置了一堆請求屬性的錯誤偵聽器,但是沒有任何工作。我怎樣才能捕捉到錯誤?

回答

9

貌似誤差從http.Client拋出,而不是請求。如何像:

var site = http.createClient(80, host); 
site.on('error', function(err) { 
    sys.debug('unable to connect to ' + host); 
}); 
var requestToRemote = site.request(...); 

僅供參考,http.createClient已被棄用 - 以下應該工作用得到方便的方法:

http.get({host: host}, function(res) { 
    ... 
}).on('error', function(e) { 
    console.log("Got error: " + e.message); 
}); 
+0

如何在回調中使用'res'值來查看回覆文本的內容? – 2012-11-02 21:21:04

-1

在運行代碼之前,您可以嘗試使用dns模塊解析主機。

http://nodejs.org/docs/latest/api/dns.html#dns.resolve

+4

這不是一個很好的解決方案,因爲這將涉及然後解析主機名兩次。即使在緩存時,仍然有一小部分可能會迅速增加,這取決於您的應用程序的需求。當然,當你發出請求時,你可以使用網絡地址而不是主機名,但是你必須處理自己指定主機的請求頭。 – Brad 2012-12-26 22:11:46

相關問題