diff --git a/tracers.ts/src/context/tracer-context.ts b/tracers.ts/src/context/tracer-context.ts index cfd856b..1f84e44 100644 --- a/tracers.ts/src/context/tracer-context.ts +++ b/tracers.ts/src/context/tracer-context.ts @@ -1,5 +1,13 @@ import type { TracerCommand } from '../types'; +const SCOPE_STATE = { + INITIAL: 'initial', + SCOPING: 'scoping', + SCOPED: 'scoped', +} as const; + +type ScopeState = (typeof SCOPE_STATE)[keyof typeof SCOPE_STATE]; + type Error = { stack?: string; }; @@ -9,15 +17,15 @@ type ScopeResult = { commands: TracerCommand[]; // 记录错误信息 error: Error; - // 检查是否多次调用scope - scoping: boolean; + // 检查scope的执行状态 + state: ScopeState; }; const createTracerContext = () => { const scopeResult: ScopeResult = { commands: [], error: {}, - scoping: false, + state: SCOPE_STATE.INITIAL, }; const command = (command: TracerCommand) => { @@ -26,11 +34,15 @@ const createTracerContext = () => { // TODO: 输出指令序列和错误信息 const flush = () => { - console.log('输出指令序列'); const { commands, error } = scopeResult; + // if (commands.length > 0 || !!error.stack) { + // console.log('输出指令序列'); + // console.log(JSON.stringify({ commands, error }, null, 2)); + // } + console.log('输出指令序列'); console.log(JSON.stringify({ commands, error }, null, 2)); - scopeResult.commands.length = 0; - scopeResult.error.stack = undefined; + scopeResult.commands = []; + scopeResult.error = {}; }; const getTracerContext = () => { @@ -40,27 +52,39 @@ const createTracerContext = () => { }; }; - const scope = (routine: () => void | PromiseLike) => { - if (scopeResult.scoping) { + const scope = (routine: () => void | Promise) => { + if (scopeResult.state === SCOPE_STATE.SCOPED) { + console.error('多次调用scope方法'); throw new Error('[TracerContext] Detect multiple scope.'); } - scopeResult.scoping = true; + if (scopeResult.state === SCOPE_STATE.SCOPING) { + console.error('嵌套调用scope方法'); + throw new Error('[TracerContext] Detect nested scope.'); + } + scopeResult.state = SCOPE_STATE.SCOPING; // 如果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(); - }); + const result = routine(); + if (result instanceof Promise) { + result + .catch((err) => { + console.log('异步错误'); + console.error(err); + scopeResult.error.stack = (err as Error).stack; + }) + .finally(() => { + scopeResult.state = SCOPE_STATE.SCOPED; + flush(); + }); + } else { + scopeResult.state = SCOPE_STATE.SCOPED; + flush(); + } } catch (err) { console.log('同步错误'); console.error(err); scopeResult.error.stack = (err as Error).stack; + scopeResult.state = SCOPE_STATE.SCOPED; flush(); } };