7

I'm trying to catch the stack trace of an node.js uncaughtException and it works fine for different errors but not for throw() statements:

Correct stack trace on exception handling:

$ cat errorFunc.js 
process.on('uncaughtException', function(exception) {
    console.log('uncaughtException occurred: ' + exception.stack);
});
MyError();

$ node errorFunc.js 
    uncaughtException occurred: ReferenceError: MyError is not defined
    at Object.<anonymous> (/home/jolcese/code/WebEnclaves/Server/errorFunc.js:5:1)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:901:3
$

Missing stack trace on exception caused by throw():

$ cat errorThrow.js 
process.on('uncaughtException', function(exception) {
    console.log('uncaughtException occurred: ' + exception.stack);
});
throw('my error');

$ node errorThrow.js 
uncaughtException occurred: undefined
$

Any idea why?

Thanks Jose

Disclaimer: I know that using process.on('uncaughtException') is a very, very bad thing and I will be punished but using domains is not an option in this code.

1
  • Keep on mind that according to MDN the stacktrace property is non-standard Commented Nov 2, 2022 at 13:23

1 Answer 1

7

JavaScript lets you throw anything.

If you want to throw errors with stack traces in JavaScript, you need to throw Error objects. (specification )

Also, throw is an operator and not a function.

Try

throw new Error('my error');

See the manual on Mozilla Developer Network for more information.

Sign up to request clarification or add additional context in comments.

3 Comments

If you'd like me to elaborate on how and why this is done on the virtual machine level (in v8) let me know. I figured that it was not relevant for solving your issue.
Thanks Benjamin for the answer!. Do you know why the behavior is different inside a Web Worker? A throw; statement inside a Web Worker call (if registered) the onerror callback providing description, lineno, colno, etc.
@JoseOlcese Yes, the simplest answer to that would be that that's because that's how they were designed. WebWorkers are a part of the web standard node doesn't adhere to. It's just WebWorkers being useful. Generally, you should always throw Error objects and not other stuff when you care about debugging (which should be always with errors)

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.