繁体   English   中英

异步javascript中抛出的异常未被捕获

[英]Exceptions thrown in asynchronous javascript not caught

基本上,为什么不抓住这个例外?

var http = require('http'),
    options = {
      host: 'www.crash-boom-bang-please.com',
      port: 80,
      method: 'GET'
    };

try {
  var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
      console.log('BODY: ' + chunk);
    });
  });

  req.on('error', function(e) {
    throw new Error("Oh noes");
  });
  req.end();
} catch(_error) {
  console.log("Caught the error");
}

有人建议用事件发射器或回调(错误)处理这些错误(有错误的回调,数据签名不是我习惯的)

什么是最好的方法呢?

当您抛出错误时, try {}块已经很久了,因为回调是在try / catch之外异步调用的。 所以你无法抓住它。

如果错误回调函数内部出现错误,请执行任何操作。

从节点版本0.8开始,您可以限制域的例外。 您可以将异常约束到某个域并在该范围内捕获它们

如果你有兴趣,我写了一个小函数来捕获异步异常: Javascript异步异常处理与node.js。 我会喜欢一些反馈这会让你执行以下操作:

var http = require('http'),
    options = {
      host: 'www.crash-boom-bang-please.com',
      port: 80,
      method: 'GET'
    };

atry(function(){
  var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
      console.log('BODY: ' + chunk);
    });
  });

  req.on('error', function(e) {
    throw new Error("Oh noes");
  });
  req.end();
}).catch(function(_error) {
  console.log("Caught the error");
});

JavaScript并没有只是功能范围,的try-catch也是块作用域。 这就是原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM