实现说明
异步边界用 await 处理,失败以 rejected promise 的形式在调用点浮出,不会被静默吞掉。Error 在 try 块内抛出——谁来接住由匹配的 except 子句决定,与任何输入检查无关。
顶层就这几处状态:channel、timeline、handlers、sum。
使用要点
- 无需安装:
node:diagnostics_channel随 Node.js 本体提供。 - 直接运行文件,输出会带上标签,比如
results :、timeline:——输出的每一行都能指回产生它的那次调用。
常见问题
这个示例会校验输入吗?
不会——Error 在 try 块内抛出:执行到这一行就必然抛出,由外围的 except 子句决定谁来接住。示例里没有输入校验。
运行之前需要装什么吗?
什么都不用装:node:diagnostics_channel 随 Node.js 本体提供。
核心语句
const loaded = await channel.tracePromise(async (id) => `user-${id}`, { op: 'loadUser' }, null, 7);
const sum = channel.traceSync((a, b) => a + b, { op: 'add' }, null, 19, 23);
throw new Error('timeout');
代码示例
import diagnostics_channel from 'node:diagnostics_channel';
const channel = diagnostics_channel.tracingChannel('app:query');
const timeline = [];
const handlers = {
start(ctx) {
timeline.push(`start:${ctx.op}`);
},
end(ctx) {
timeline.push(`end:${ctx.op}`);
},
asyncEnd(ctx) {
timeline.push(`asyncEnd:${ctx.op}`);
},
error(ctx) {
timeline.push(`error:${ctx.op}:${ctx.error.message}`);
},
};
channel.subscribe(handlers);
const sum = channel.traceSync((a, b) => a + b, { op: 'add' }, null, 19, 23);
const loaded = await channel.tracePromise(async (id) => `user-${id}`, { op: 'loadUser' }, null, 7);
try {
channel.traceSync(() => {
throw new Error('timeout');
}, { op: 'ping' });
} catch {
// Error hook already captured the fault
}
channel.unsubscribe(handlers);
console.log('results :', sum, loaded);
console.log('timeline:', timeline.join(' -> '));