我试图了解如何从 setTimeout
引起的 promise 拒绝中获取完整的堆栈跟踪
我正在运行以下示例:
'use strict';
function main() {
f1().catch(e => {
console.error('got error with trace:');
console.error(e);
});
f2().catch(e => {
console.error('got error with trace:');
console.error(e);
});
}
async function f1() {
return new Promise((resolve, reject) => {
reject(new Error('Error in normal flow'));
});
}
async function f2() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('Error in timeout'));
}, 0);
});
}
main();
我得到了这个输出:
got error with trace:
Error: Error in normal flow
at Promise (/Users/me/project/example.js:25:12)
at Promise (<anonymous>)
at f2 (/Users/me/project/example.js:24:10)
at main (/Users/me/project/example.js:9:3)
at Object.<anonymous> (/Users/me/project/example.js:29:1)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
got error with trace:
Error: Error in timeout
at Timeout.setTimeout [as _onTimeout] (/Users/me/project/example.js:18:14)
at ontimeout (timers.js:488:11)
at tryOnTimeout (timers.js:323:5)
at Timer.listOnTimeout (timers.js:283:5)
如何使使用 setTimeout 启动的 Promise 的堆栈跟踪更加详细,就像没有 setTimeout
的 Promise 一样?
当这种情况在实际生产代码中发生在我身上时,我无法确切知道错误是从哪里发起的。这使得调试非常困难。
最佳答案
我之前做过类似以下的事情:
async function f2() {
return new Promise((resolve, reject) => {
const potentialError = new Error('Error in timeout');
setTimeout(() => {
reject(potentialError);
}, 0);
});
}
这会导致一个错误,就像 setTimeout
之外的错误一样。无论您在何处创建错误,这都将决定您的堆栈跟踪。
对我来说,这个用例的一个用例是一个超时的测试,因为 promise 永远不会解决(在我的例子中,使用木偶师和摩卡/ Jasmine )。因为超时没有有意义的堆栈跟踪,所以我写了 a wrapper around the promise that includes a setTimeout
,很像这个例子。
关于javascript - 如何使用 Promise 查看 setTimeout 中错误的完整堆栈跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46528508/