Reputation: 1076
I've been working on trying to add some better error logging to a web application that is only run on Chrome. In essence, I want to be able to capture and store stack traces. For synchronous code, this works fine, but for async code, I've run into something a tad strange. Essentially, Chrome appears to log additional information as part of its async stack trace feature, but I haven't been able to figure out how to capture it.
Code, to run in Chrome browser console:
let e;
let a = () => Promise.resolve(null)
.then(() => (null).foo)
.catch(err => {
console.info(err);
console.error(err);
e = err;
})
let b = () => a();
let c = () => b();
c();
Output:
(info)
TypeError: Cannot read property 'foo' of null
at <anonymous>:3:20
(error, after expanding)
TypeError: Cannot read property 'foo' of null
at <anonymous>:3:20
(anonymous) @ VM1963:6
Promise.catch (async)
a @ VM1963:4
b @ VM1963:9
c @ VM1963:10
(anonymous) @ VM1963:11
So console.error
gives me a stack trace threaded all the way through the callstack, presumably through some form of Chrome engine magick. console.info
gives me the actual stack trace that's stored on err
. If after this is all done I attempt to read the value of e
, its stack is the two lines I get from the console.info
statement, not the console.error
statement.
What I'm asking is, is there any way to capture and store the async stack trace that Chrome is generating and using when I call console.error
?
Upvotes: 20
Views: 1396
Reputation: 16885
console.error()
seems to invoke console.trace()
as a matter of convenience.
It doesn't look like a script can get the stack trace as anything other than a string. That string can be had with, for example, err.stack
. MDN has documentation for the stack
property of Error
. It's not part of a spec but seems to be supported across all platforms.
Upvotes: 2