Save stack traces in node.js
I am trying to keep the call stack while handling errors arising from eg net.js.
Below is an example, but I need to preallocate an error object for each call that is not optimal.
function socketStuff(callback) {
// ..
var maybeError = new Error 'Socket error ';
socket.on('error', function(error) {
maybeError.message += error.message;
callback(maybeError);
});
}
Is there a way to add the stack I get from creating an error in the context of a function to the error I get from the socket without first creating the error object?
source to share
You need to get the stack trace up front at the point of your call new Error()
. You don't need to create an actual Error object; you can also use the V8 stack trace API :
var stackHolder = {};
Error.captureStackTrace(stackHolder, nameOfCurrentFunction);
and now the stack is available as stackHolder.stack
.
V8 lazy - formats the stack, so it's not as expensive as you might think; that property stack
is a getter property that, when first run, does the formatting and then replaces the result with itself. (From the docs cited above: "For stack traces, efficiency is not formatted when captured, but on demand when a stack property is first accessed.")
source to share