docs(tracer-context): 添加详细的中文注释说明scope的设计原理和实现细节。
This commit is contained in:
@@ -56,6 +56,13 @@ const createTracerContext = () => {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
// 由于JavaScript/TypeScript在语言层面缺乏统一的“程序退出钩子”机制,
|
||||||
|
// 所以我们无法在算法执行结束后自动地输出指令序列和异常信息,
|
||||||
|
// 尽管像Node.js这样的运行时提供了process.on('exit'),但是我们希望保持SDK的环境无关性,
|
||||||
|
// 所以为了不依赖于特定运行时的API,我们设计了scope方法来创建一个显式的生命周期,
|
||||||
|
// 算法逻辑将会被一个回调函数包裹,作为routine参数,
|
||||||
|
// 在routine执行完毕后,scope会向外输出指令序列和异常信息。
|
||||||
const scope = (routine: () => void | Promise<void>) => {
|
const scope = (routine: () => void | Promise<void>) => {
|
||||||
if (scopeResult.state === SCOPE_STATE.SCOPED) {
|
if (scopeResult.state === SCOPE_STATE.SCOPED) {
|
||||||
throw new ScopeError('ScopeError: Detect multiple scope.');
|
throw new ScopeError('ScopeError: Detect multiple scope.');
|
||||||
@@ -67,19 +74,23 @@ const createTracerContext = () => {
|
|||||||
// 如果routine是同步函数,那可能会抛出同步错误,所以需要用try-catch包裹
|
// 如果routine是同步函数,那可能会抛出同步错误,所以需要用try-catch包裹
|
||||||
try {
|
try {
|
||||||
const result = routine();
|
const result = routine();
|
||||||
|
// 如果routine是异步函数,需要用catch捕获异步错误
|
||||||
if (result instanceof Promise) {
|
if (result instanceof Promise) {
|
||||||
result
|
result
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
|
// 如果是ScopeError,需要抛出,否则会在嵌套调用scope时被外层scope捕获
|
||||||
if (error instanceof ScopeError) {
|
if (error instanceof ScopeError) {
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
scopeResult.exception.stack = (error as Error).stack;
|
scopeResult.exception.stack = (error as Error).stack;
|
||||||
})
|
})
|
||||||
.finally(() => {
|
.finally(() => {
|
||||||
|
// 无论是否有异常,都需要设置本次的scope状态
|
||||||
scopeResult.state = SCOPE_STATE.SCOPED;
|
scopeResult.state = SCOPE_STATE.SCOPED;
|
||||||
flush();
|
flush();
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
|
// 如果routine是同步函数,执行完成后需要设置scope状态
|
||||||
scopeResult.state = SCOPE_STATE.SCOPED;
|
scopeResult.state = SCOPE_STATE.SCOPED;
|
||||||
flush();
|
flush();
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user