1

NodeJS v0.10.31 under OS X, same behavior under NodeJS v0.12.2.

My stack trace doesn't show the test function name when called normally:

function test() {
  throw new Error('Missing `test` in stack trace?');
}

try {
  test();
} catch (e) {
  console.trace(e);
}

Output:

Trace: [Error: Missing `test` in stack trace?]
    at Object.<anonymous> (no_stack_in_node.js:8:11)
    // etc.

If it's inside a setTimeout I see what I expect:

try {
  setTimeout(test, 0);
} catch (e) {
  console.trace(e);
}

Output:

Error: Missing `test` in stack trace?
    at test [as _onTimeout] (no_stack_in_node.js:2:9)
    at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)

In the browser I see the latter in both cases.

Is there something specific I'm missing, or is the environment of NodeJS's CLI interfering, e.g., the "top level object" behaves a bit differently?

Dave Newton
  • 152,765
  • 23
  • 240
  • 286

2 Answers2

3

Try to replace console.trace(e) with console.log(e.stack), and you will get:

Error: Missing `test` in stack trace?
    at test (no_stack_in_node.js:2:11)
    at Object.<anonymous> (no_stack_in_node.js:8:11)

When you do console.trace you print the stack trace of the place where you are (it is not required that the object is an error, you can just say console.trace('hello')), that is, inside the catch block.

If you want to get the stack trace of the error, you must read the trace from it (e.stack). Once read, you can log it, or whatever you need.

greuze
  • 3,778
  • 4
  • 38
  • 60
2

In Node.js, all the code in a module will be wrapped in an anonymous function, like this

(function (exports, require, module, __filename, __dirname) {
    // our actual module code
});

So your actual code will be wrapped like this

(function (exports, require, module, __filename, __dirname) {
    function test() {
        throw new Error('Missing `test` in stack trace?');
    }

    try {
        test();
    } catch (e) {
        console.trace(e);
    }
});

See this answer for a detailed explanation.

So, when you are tracing the location of the e, it actually is in an anonymous function. That is why it says Object.<anonymous>

Community
  • 1
  • 1
thefourtheye
  • 206,604
  • 43
  • 412
  • 459
  • Shouldn't the `test()` function still be somewhere in the stack trace? The code **does** throw from within it - it should be right next to the anonymous function. – Robert Rossmann Jun 07 '15 at 16:35
  • @RobertRossmann `test` has thrown the exception, the stack unwinds and `test` will not be in the stack at this point. – thefourtheye Jun 07 '15 at 16:36