javascript - 如何处理 http.get 响应中未捕获的异常

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

我有这段代码可以使用 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 throw arguments[1]; // Unhandled 'error' event ^ Error: Parse Error at Socket.socketOnData (http.js:1367:20) at 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);

最佳答案

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

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

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

关于javascript - 如何处理 http.get 响应中未捕获的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14393162/

相关文章:

javascript - 从企业防火墙后面调用 RESTful 服务时出现 CORS 错误

javascript - jQuery 事件不绑定(bind)

javascript - async wait 实用函数同步?

java - Play Framework : Redirect to controller method with arguments

json - 如何使我的 Apex 类返回或 "run"JSON?使用 APEX REST

javascript - 为什么我的 Meteor API 调用抛出异常?

javascript - 仅在网站可用时重定向浏览器

javascript - jquery 导出表到 excel 以指数形式更改值

javascript - Firefox Nodejs Websocket

javascript - 如何在 Windows 上检查 Meteor.js 的版本