2014-07-17 2 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