Joao Joao - 7 months ago 11
Javascript Question

Throw new Error doesn't throw and node.js don't complain about nonexistent variables

I'm believe i'm having some problem with node.js, for at least 4 months, but just now i want fix. I already try to re-install, currently i'm using 6.0.0.

My throw new Error('message'); are being ignored by the engine, when i try to do:

console.log('test');
throw new Error('error');
console.log('test');


I see only:

test
test


Also, when i try to console.log in nonexistent variables, nothing happens.

What could be?

Thanks.

Answer

It seems likely there is something about the context of your code that is confusing you. We could help you figure that out if you showed us the context of this code and if you change what the second console.log('test'); outputs so you could tell the difference between the second log statement executing vs. your code just getting called twice (which is my guess).

And, as a vanilla test of your node installation, I'd suggest that you take this set of code and put it in a file named throw-test.js and run just that file:

// throw-test.js

try {
    console.log('test1');
    throw new Error('error');
    console.log('test2');
} catch(e) {
    console.log('log exception');
}

You should see this in the console when you run node throw-test.js:

test1
log exception

That's exactly what I see in my running node.js and is what would be expected.


Other things that could be confusing the situation:

  1. Your code might be getting called twice and that's why you get the output you get.
  2. Your code might be inside an async callback that eats exceptions (that's why you don't see any exception logged).
  3. You have a console.log('test') somewhere else in your code and that's why you see two of them.

As for your other comment, the code:

console.log(nonExistent);

will throw a ReferenceError exception. Whether you see that exception or not in your logs depends upon where this code is. Again, if it's inside an async callback, the exception may be eaten (depends upon the specific callback).