实现说明
除了函数 runWithFailingCleanup,文件里再无其他定义。
这个示例中仅有的重复出现在 while (cursor instanceof SuppressedError) 里。Error 在其所在位置无条件抛出——前面没有任何输入检查。
使用要点
- 运行过程中不会加载任何第三方代码。
- 跑完文件,输出里会留下标记——
caught SuppressedError:、root error:。
常见问题
这个示例会校验输入吗?
不会。示例里没有输入校验——Error 在其所在位置无条件抛出,前面没有任何检查。
这份代码可以原样复制进项目使用吗?
可以。粘进去就能运行,中间没有包管理器的事。 文件在加载时定义 runWithFailingCleanup。
主要签名是 function runWithFailingCleanup()
核心语句
throw new Error('close socket failed');
throw new Error('query timed out');
代码示例
function runWithFailingCleanup() {
using stack = new DisposableStack();
stack.defer(() => {
throw new Error('close socket failed');
});
// Primary body also throws while stack unwinds at block exit
throw new Error('query timed out');
}
try {
runWithFailingCleanup();
} catch (err) {
console.log('caught SuppressedError:', err instanceof SuppressedError);
let cursor = err;
let depth = 0;
// Walk .error (cleanup) and .suppressed (original cause) links
while (cursor instanceof SuppressedError) {
console.log(`[${depth}] cleanup=${cursor.error.message} | masked=${cursor.suppressed.message}`);
cursor = cursor.suppressed;
depth++;
}
console.log('root error:', cursor.message);
}