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

cha*_*log 9 javascript asynchronous exception-handling node.js

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

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");
}
Run Code Online (Sandbox Code Playgroud)

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

什么是最好的方法呢?

Thi*_*ter 11

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

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


Ben*_*aum 5

从节点版本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");
});
Run Code Online (Sandbox Code Playgroud)