Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing stack trace on node.js uncaughtException generated by throw()

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.

like image 987
JoseOlcese Avatar asked May 23 '13 16:05

JoseOlcese


People also ask

What is node error?

An error in Node. js is any instance of the Error object. Common examples include built-in error classes, such as ReferenceError , RangeError , TypeError , URIError , EvalError , and SyntaxError .

How do you catch uncaught exception?

In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution. In other words, you can "try" to execute a block of code, and "catch" any exceptions that are thrown.


1 Answers

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.

like image 73
Benjamin Gruenbaum Avatar answered Nov 09 '22 23:11

Benjamin Gruenbaum