The following code sample:
async function expectResolutionErrorCode(object) {
try {
await Promise.resolve(1);
object.f1() // caught error
} catch (error) {
object.f2() // uncaught error
}
}
expectResolutionErrorCode(undefined).catch(err => console.log(err));
Produces the following backtrace when run using node v14:
$ node test.ts
TypeError: Cannot read property 'f2' of undefined
at expectResolutionErrorCode (/Users/bogdan/makabu/unstoppable/resolution/test.ts:6:12)
If I comment out the await statement at line 3 from the sample, the backtrace is complete:
TypeError: Cannot read property 'f2' of undefined
at expectResolutionErrorCode (/Users/bogdan/makabu/unstoppable/resolution/test.ts:6:12)
at Object.<anonymous> (/Users/bogdan/makabu/unstoppable/resolution/test.ts:10:1)
at Module._compile (internal/modules/cjs/loader.js:1201:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1221:10)
at Module.load (internal/modules/cjs/loader.js:1050:32)
at Function.Module._load (internal/modules/cjs/loader.js:938:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
So the await statement clearly causes node to lose some part of the backtrace.
Why does it behave like that?
Is there any workaround to maintain the backtrace while still using await statements inside try catch?
I tested this behavior in Chrome and Safari and the stacktrace is lost in almost the same way: https://jsfiddle.net/61kdv8fx/