domain.intercept(callback)
callback<Function> 回调函数- 返回:<Function> 被拦截的函数
此方法几乎与 domain.bind(callback) 相同。然而,除了捕获抛出的错误外,它还会拦截作为函数第一个参数传入的 Error 对象。
【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.】
通过这种方式,常见的 if (err) return callback(err); 模式可以被单个地方的统一错误处理器所取代。
【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.
});