3

In Node, is there a way to add a line or value to the stack trace, in case of an error downstream?

I know there are LOTS of other ways to make the data available. And I am aware that the trace is not meant for value storage. But I'm wondering if this specific idea is doable (within reason).

2 Answers 2

4

The stacktrace contains all the called functions, so that seems to be the only way, to add a function to it as an iIFE:

(function executedSomeCode() {
  throw new Error("failure");
})();

Now your stacktrace contains:

...
at executedSomeCode
...

Or you just edit the stack property of the error:

var error = new Error();
error.stack += "\nhey, whats up?";
throw error;
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the response. Unfortunately both of those manipulations occur at the point of an error and what I'm looking to do is seed something in the stack (further upstream), so that if an error occurs further along, the value/message is in the stack. After doing some further research, I don't think this is possible without mocking up one's own stack trace (for which there are libraries and methods). I'm going to close out this question.
@astanelo you could still catch, modify and rethrow the error.
True. Catch the error where it occurred and trace it out where I have the needed data. That's a good suggestion. Still would be interesting if I could modify the stack. :)
@astangelo you could just modify the error.stack property. Thats "modifying the stack" and I can't give a better advice without a better usecase.
1

After some further research, I don't think this is possible. Neither Javascript, V8, nor Node.js expose the stack in an editable fashion, which makes some sense. However, I did come across some useful links, worth sharing:

  • V8 Stack Trace API ReadMe - Explains tracing methods, native to V8, including manipulating the stack length and capturing the stack.
  • Manipulating Stack Traces - Has a great explanation of how to OMIT methods from a stack trace.
  • Function Caller method - MDN explanation of the caller() method and how you could use it to mock-up your own stack trace, to a degree. (pretty cool result).
  • Node.js Tracing API - This is somewhat barebones but it does cover flags.
  • DIY Stack Trace - It's cutesy and from 2007 but the explains how you could make your own stack trace.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.