【问题标题】:how to handle uncaught exception in http.get response如何处理 http.get 响应中未捕获的异常
【发布时间】:2013-01-18 05:52:53
【问题描述】:

我有这段代码可以使用 API 从第三方网站下载新闻提要。其设置为每 5 秒运行一次,并提取可能发生的任何新闻事务。问题似乎在于没有发生新事务时。

通过添加 process.on('uncaught exception', function(error){ console.log("hmph") }) cron 作业可以在 5 秒后继续,所以我很想保持原样;但是,我添加了 console.log("hmph") ,现在我很困惑。

第一次,控制台会写hmph。 5秒后它会写 哼哼 哼

等等。我知道我一定错过了什么,但我不太确定它是什么。我已经尝试在 else 语句中执行 request.end() 但错误仍然会触发。

没有 process.on('uncaught...') 抛出的错误是:

events.js:71 抛出参数[1]; // 未处理的“错误”事件 ^ 错误:解析错误 在 Socket.socketOnData (http.js:1367:20) 在 TCP.onread (net.js:403:27)

使用 proccess.on('uncaught...'),console.log(error) 是:

{ [Error: Parse Error] bytesParsed: 161, code: 'HPE_INVALID_CONSTANT' }

如何正确处理此错误?

缩写代码:

var job = new cronJob('*/5 * * * * *', function(){
  var request = http.get({
                            host: 'www.example.com',
                            path: '/news_feed?apicode=myapicode',
                            port: 80,
                            headers: { 'accept-encoding': 'gzip' } 
                         })

  request.on('response', function(response){
    if (response.statusCode == 200){
      // gunzip response, save response to mongodb
    } 
    else
    {
      // here is where the error is occuring
      process.on('uncaughtException',function(error){
        console.log(error);
        console.log("hmph");
    }
  });
}, null, true);

【问题讨论】:

    标签: javascript node.js http-get uncaught-exception eventemitter


    【解决方案1】:

    每次发出请求时,都会绑定一个新的uncaughtException 处理程序,因此当发送第一个请求时,会绑定第一个请求,失败时会打印错误,然后在下一个请求时,您添加另一个处理程序,当失败时,第一个和第二个处理程序都将运行。

    检查错误,并在此处讨论此类错误:https://github.com/joyent/node/issues/3354 您连接的服务器似乎正在做一些奇怪的事情。对您来说最简单的解决方案可能是现在使用 uncaughtException 处理程序。也就是说,它并不理想,您不应该将其作为未来此类问题的通用解决方案。

    var job = new cronJob('*/5 * * * * *', function(){
      var request = http.get({
        host: 'www.example.com',
        path: '/news_feed?apicode=myapicode',
        port: 80,
        headers: { 'accept-encoding': 'gzip' } 
      });
      request.on('response', function(response){
        if (response.statusCode == 200){
          // gunzip response, save response to mongodb
        }
      });
    }, null, true);
    
    process.on('uncaughtException',function(error){
      console.log(error);
      console.log("hmph");
    });
    

    【讨论】:

    • 感谢您的回答;但是,我已经尝试过这样做并且得到: events.js:71 throw arguments[1]; // 未处理的“错误”事件 ^ 错误:在 TCP.onread (net.js:403:27) 的 Socket.socketOnData (http.js:1367:20) 处解析错误
    • 你确定你在我说的同一个地方绑定?您不会将错误放在响应回调中,就像您有 uncaughtException 处理程序一样
    • 是的,我查过了,它在同一个地方。这是带有您的建议的完整代码。 pastebin.com/PTu7cA8s
    • 在那个代码中哎呀,第 28 行 .on('error') 是我试图在差异点中测试它的东西。无论哪种方式,仍然会发生相同的错误。我真的很感谢你的帮助:)
    • 感谢您的帮助。有没有办法清除旧的错误处理程序,所以它们不只是累积?我担心最终会有大量的处理程序,这可能会产生什么影响?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-10
    • 2011-10-27
    • 2017-11-25
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多