2014-07-17 26 views
0

我想用一些通用的錯誤處理代碼替換if(body.toString().indexOf("404") !== 0)塊,但是我似乎無法看到目標主機關閉時引發錯誤的位置。到目前爲止,這是我設法組合起來的唯一可行的方法。如何處理站點關閉時的http調用錯誤

app.get('/', function(req, res){ 
    var sites = ["foo.com", "bar.com"]; 
    var returnObj = []; 
    var index = 0; 
    getSites(index); 

    // Recursively add data from each site listed in "sites" array 
    function getSites(index) { 
     if(index < sites.length) { 
      var url = sites[index]; 
      var _req = http.get({host: url}, function(_res) { 
       var bodyChunks = []; 
       _res.on('data', function(chunk) { 
       bodyChunks.push(chunk); 
       }).on('end', function() { 
       var body = Buffer.concat(bodyChunks); 
       if(body.toString().indexOf("404") !== 0) { 
        returnObj.push(JSON.parse(body)); 
       }  
       getSites(++index); 
       }); 
      }); 

      _req.on('error', function(e) { 
       console.log('ERROR: ' + e.message); 
      }); 
     } else { 
      res.json(returnObj); 
      res.end(); 
     } 
    } 
}); 

回答

1

您可以檢查響應的狀態代碼。

if(_req.statusCode === 200) { 
    //Response okay. 
} 

Here's狀態碼列表。

+0

謝謝,dawg :) – roscioli