4

使用同步错误,您可以像这样嵌套错误范围:

try {
  try {
    throw Error('e')
  } catch(e) {
    if(e.message !== 'f')
      throw e
  }
} catch(e) {
  handleError(e)
}

这就是我期望它工作的方式,但它没有(似乎域错误处理程序中的错误被抛出到顶部,跳过中间的任何域):

var domain = require('domain');
var dA = domain.create();
dA.on('error', function(err) {
    console.log("dA: "+ err); // never happens
});
dA.run(function() {
    var dB = domain.create();
    dB.on('error', function(err) {
        throw err
    });
    dB.run(function() {
        setTimeout(function() {
            console.log('dB')
            throw 'moo'
        },0)
    });
});

有没有办法做到这一点?

4

1 回答 1

5

通过重新抛出,冒泡在域中不起作用。如果您想将错误传递给您知道可以处理错误的另一个域,您可以直接在该域上重新发出错误事件:

var domain = require('domain');
var dA = domain.create();
dA.on('error', function(err) {
    console.log("dA: "+ err); // never happens
});
dA.run(function() {
    var dB = domain.create();
    dB.on('error', function(err) {
        dA.emit('error', err);
    });
    dB.run(function() {
        setTimeout(function() {
            console.log('dB')
            throw 'moo'
        },0)
    });
});

稍微扩展一下,从域的错误处理程序中抛出的问题是它直接传播到顶层,更令人困惑的是,如果抛出是错误处理程序中错误的结果,那么打印的堆栈跟踪out 来自您的原始错误,而不是处理程序中的错误。从理论上讲,可以将异常冒泡到堆栈中,但这不是域的设计方式。

The "nested" domains will work properly if the handler of an outer domain throws while an inner domain is active, but what it does in that case is give the error to the outer domain's error handler and then exits both the outer and the nested domain. This mimics how a catch unwinds the stack in the try/catch case, but it can be a little confusing.

于 2013-10-28T07:37:59.373 回答