Why does the stack trace of an Error that is returned by a Promise seem to be incomplete?
Solution 1:
Async stack traces (the ones you get in production) only work with async functions so when you have a function that isn't async and just uses promises the chain won't stitch. You can read more on the implementation in the design document the fix fortunately is pretty simple:
// the function has to be async
async function a() {
// isolate areas that have to use raw promises
await new Promise((resolve, reject)=>{
setTimeout(()=>resolve(), 2000);
});
// throw the error from inside the function
throw new Error('a');
}
Which happily logs:
Error: a
at a (<anonymous>:6:11)
at async b (<anonymous>:10:5)
at async c (<anonymous>:14:5)
at async test (<anonymous>:23:5)
Solution 2:
I could be wrong but I believe its because you create an anonymous function within setTimeout, which would then be thrown for the error.
Maybe not the cleanest, but for every Error I put in a logPrefix, and do something like the below. Just means you can easily debug an error.
const logPrefix = '[my-function-name]'
throw new Error(`${logPrefix} - The error maybe with ${error} injected`)
If my function is within a class or something I might do the below
const logPrefix = '[className.methodName]'