Preserve Stack Traces In Node.js
I'm trying to preserve the call stack when handling errors that comes from e.g. net.js. The example below works but requires me to pre-allocate an error object for every call which
Solution 1:
You do have to acquire the stack trace up front, at the point of your new Error()
call. You don't have to create an actual Error object; you can also use the V8 stack trace API to do it:
var stackHolder = {};
Error.captureStackTrace(stackHolder, nameOfCurrentFunction);
and now the stack is available as stackHolder.stack
.
V8 lazy-formats the stack so this isn't as expensive as you might think; that stack
property is actually a property getter which the first time it's run does the formatting work and then replaces itself with the output. (From the docs linked above: "For efficiency stack traces are not formatted when they are captured but on demand, the first time the stack property is accessed.")
Solution 2:
Just use one of existing long stack traces library, for example this one
Post a Comment for "Preserve Stack Traces In Node.js"