From 8894458f4cfd92c6ff79efe92d1e1fa64d9763ac Mon Sep 17 00:00:00 2001 From: skycurtain Date: Sun, 22 Feb 2026 22:37:06 +0800 Subject: [PATCH] =?UTF-8?q?feat(tracer-context):=20=E6=B7=BB=E5=8A=A0scope?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E4=BB=A5=E6=94=AF=E6=8C=81=E8=BF=BD=E8=B8=AA?= =?UTF-8?q?=E5=BC=82=E6=AD=A5=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增scope方法用于包裹异步或同步代码块,自动捕获错误并记录到上下文中。同时将dump方法重命名为flush以更准确描述其行为(清空并输出指令序列)。重构内部数据结构,将commands和error统一管理在scopeResult对象中。 --- tracers.ts/src/context/tracer-context.ts | 79 ++++++++++++++++++------ 1 file changed, 59 insertions(+), 20 deletions(-) diff --git a/tracers.ts/src/context/tracer-context.ts b/tracers.ts/src/context/tracer-context.ts index adef36a..cfd856b 100644 --- a/tracers.ts/src/context/tracer-context.ts +++ b/tracers.ts/src/context/tracer-context.ts @@ -1,35 +1,74 @@ import type { TracerCommand } from '../types'; -const createTracerContext = () => { - const commands: TracerCommand[] = []; +type Error = { + stack?: string; +}; - // if (typeof process !== 'undefined' && typeof process.on === 'function') { - // process.on('exit', () => { - // if (commands.length > 0) { - // console.log(commands); - // } - // }); - // } +type ScopeResult = { + // 记录指令序列 + commands: TracerCommand[]; + // 记录错误信息 + error: Error; + // 检查是否多次调用scope + scoping: boolean; +}; + +const createTracerContext = () => { + const scopeResult: ScopeResult = { + commands: [], + error: {}, + scoping: false, + }; + + const command = (command: TracerCommand) => { + scopeResult.commands.push(command); + }; + + // TODO: 输出指令序列和错误信息 + const flush = () => { + console.log('输出指令序列'); + const { commands, error } = scopeResult; + console.log(JSON.stringify({ commands, error }, null, 2)); + scopeResult.commands.length = 0; + scopeResult.error.stack = undefined; + }; const getTracerContext = () => { - const command = (command: TracerCommand) => { - commands.push(command); - }; - - // TODO: 输出指令序列 - const dump = () => { - return commands; - }; - return { command, - dump, + flush, }; }; + const scope = (routine: () => void | PromiseLike) => { + if (scopeResult.scoping) { + throw new Error('[TracerContext] Detect multiple scope.'); + } + scopeResult.scoping = true; + // 如果routine是同步函数,那可能会抛出同步错误,所以需要用try-catch包裹 + try { + const promise = Promise.resolve(routine()); + promise + .catch((err) => { + console.log('异步错误'); + console.error(err); + scopeResult.error.stack = (err as Error).stack; + }) + .finally(() => { + flush(); + }); + } catch (err) { + console.log('同步错误'); + console.error(err); + scopeResult.error.stack = (err as Error).stack; + flush(); + } + }; + return { getTracerContext, + scope, }; }; -export const { getTracerContext } = createTracerContext(); +export const { getTracerContext, scope } = createTracerContext();