astangelo
astangelo

Reputation: 627

Add value to Stack Trace, Javascript

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).

Upvotes: 2

Views: 2087

Answers (2)

astangelo
astangelo

Reputation: 627

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.

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138257

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;

Upvotes: 2

Related Questions