Run this code in Chrome 59 and in Node.js and you will notice there is a difference in output.
var e = new Error('first');
console.log(e);
e.message = 'new';
console.log(e);
It appears that node is caching the object so it looks the same at both console.log(e)
when the message property actually changed.
Note this also happens on Node 7.9.0, Node 8.0.0, and Node 8.1.2 so it's unclear if this is a bug or expected behavior.
This question originated on StackOverflow.
This is expected because what you're seeing is the stack trace, which includes the error message once it's generated. The stack trace is generated lazily and only once (for performance reasons), so that is why you see the same output both times.
If you however change your code to output e.message
, you will see the expected change in output.
@mscdex Thanks! But why does Chrome has different behavior than Node?
It's just a difference in how non-string values are "inspected." Node internally uses util.inspect()
in console.log()
. I don't know offhand what logic Chrome uses, but it's obviously different.
Here is where util.inspect()
specifically checks for an Error
object. It then formats it by checking for a stack (which is a getter on Error
instances and thus gets chosen in most cases) and falling back to a conversion of the object to a string.
Most helpful comment
This is expected because what you're seeing is the stack trace, which includes the error message once it's generated. The stack trace is generated lazily and only once (for performance reasons), so that is why you see the same output both times.
If you however change your code to output
e.message
, you will see the expected change in output.