Using Declarations Dispose On Scope Exit

Wire cleanup into scoping with using: the runtime calls Symbol.dispose on block exit in reverse order, and the error path disposes before the throw propagates.

JavascriptResilience

Code

javascriptsnippet
40 lines
class Tracer {
  #events = [];

  span(name) {
    const events = this.#events;
    events.push(`enter ${name}`);
    return {
      [Symbol.dispose]() {
        events.push(`exit ${name}`);
      },
    };
  }

  log() {
    return [...this.#events];
  }
}

// using:作用域结束(含异常退出)自动调用 Symbol.dispose,等价 try/finally
function handle(tracer) {
  using outer = tracer.span('outer');
  {
    using inner = tracer.span('inner');
    console.log('work inside both spans');
  }
  console.log('inner disposed, outer still open');
}

const tracer = new Tracer();
handle(tracer);
console.log(tracer.log().join(' -> '));

// 异常路径:先逆序执行 dispose,异常才继续向外传播
try {
  using failing = tracer.span('failing');
  throw new Error('boom');
} catch (err) {
  console.log('caught:', err.message);
}
console.log(tracer.log().slice(-2).join(' -> '));

Output

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

work inside both spans
inner disposed, outer still open
enter outer -> enter inner -> exit inner -> exit outer
caught: boom
enter failing -> exit failing

Inside the snippet

Using Declarations Dispose On Scope Exit keeps everything in the class Tracer and the function handle.

Error is thrown inside a try block — the matching handler clause, not any input check, decides what happens to it.

Returns a newly built value, leaving the inputs as they were.

Using it

The main signature reads function handle(tracer)

Running the file prints labeled results such as work inside both spans, inner disposed, outer still open, caught: — each operation’s effect is visible in the output.

Key statements

return [...this.#events];
throw new Error('boom');

Interactive Tools for This Topic

FAQ

Does `handle` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
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.
Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. The file defines `handle` at load time.