tracingChannel Hooks Sync and Promise Spans Cleanly

Subscribe to node:diagnostics_channel tracingChannel lifecycle events around traceSync and tracePromise without coupling hooks to business logic.

JavascriptResilience

Code

snippet
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(' -> '));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

results : 42 user-7
timeline: start:add -> end:add -> start:loadUser -> end:loadUser -> asyncEnd:loadUser -> start:ping -> error:ping:timeout -> end:ping

Execution path — tracingChannel Hooks Sync and Promise Spans Cleanly

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Error is thrown inside a try block — the matching handler clause, not any input check, decides what happens to it.

The file’s state is a handful of top-level bindings: channel, timeline, handlers, sum.

Caveats

  • No install needed: node:diagnostics_channel comes with Node.js itself.

Using it

Output lines are prefixed (results :, timeline:), verifying every logical step clearly through labeled log rows.

Key statements

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');

Interactive Tools for This Topic

FAQ

Does the snippet validate its input?
No — the `Error` is raised inside a `try` block: execution reaches it unconditionally, and the surrounding handler clause decides what catches it. There is no input check in the snippet.
Do I need to install anything before running this?
Nothing needs installing: `node:diagnostics_channel` ships with Node.js itself.