domain.intercept(callback)


此方法和 domain.bind(callback) 差不多。 但是,除了捕获抛出的错误外,它还会拦截作为第一个参数发送给函数的 Error 对象。

这样,常见的 if (err) return callback(err); 模式可以在一个地方用单个错误句柄替换。

const d = domain.create();

function readSomeFile(filename, cb) {
  fs.readFile(filename, 'utf8', d.intercept((data) => {
    // 注意,第一个参数永远不会传给回调,
    // 因为它被假定为 'Error' 参数,
    // 因此被域拦截。

    // 如果这抛出,
    // 则它也将被传到域,
    // 因此错误处理逻辑可以移动到域上的 'error' 事件,
    // 而不是在整个程序中重复。
    return cb(null, JSON.parse(data));
  }));
}

d.on('error', (er) => {
  // 某处发生了错误。如果我们现在抛出,
  // 则其会以正常的行号和堆栈消息使程序崩溃。
});

This method is almost identical to domain.bind(callback). However, in addition to catching thrown errors, it will also intercept Error objects sent as the first argument to the function.

In this way, the common if (err) return callback(err); pattern can be replaced with a single error handler in a single place.

const d = domain.create();

function readSomeFile(filename, cb) {
  fs.readFile(filename, 'utf8', d.intercept((data) => {
    // Note, the first argument is never passed to the
    // callback since it is assumed to be the 'Error' argument
    // and thus intercepted by the domain.

    // If this throws, it will also be passed to the domain
    // so the error-handling logic can be moved to the 'error'
    // event on the domain instead of being repeated throughout
    // the program.
    return cb(null, JSON.parse(data));
  }));
}

d.on('error', (er) => {
  // An error occurred somewhere. If we throw it now, it will crash the program
  // with the normal line number and stack message.
});