Reputation: 160261
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?
Upvotes: 0
Views: 1556
Reputation: 4398
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.
Upvotes: 3
Reputation: 239573
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>
Upvotes: 2