【问题标题】:How to handle error of http call when site is down站点关闭时如何处理http调用错误
【发布时间】:2014-07-17 15:45:59
【问题描述】:

我想用一些通用的错误处理代码替换if(body.toString().indexOf("404") !== 0) 块,但是当目标主机关闭时,我似乎看不到它在哪里引发错误。到目前为止,这是我设法组合起来的唯一可行的 hacky 方法。

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();
        }
    }
});

【问题讨论】:

    标签: javascript node.js asynchronous error-handling http-get


    【解决方案1】:

    您可以查看响应的状态码。

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

    Here's 状态码列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-21
      • 2019-03-04
      • 2011-04-22
      • 1970-01-01
      • 2015-03-31
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      相关资源
      最近更新 更多