In NodeJS (same applies to Javascript in browser), why doesn't JSON.stringify(new Error('huh'))
print out the Error.message property?
I was debugging some NodeJS code dealing with a file open error and used JSON.stringify()
to the Error object, and was surprised when I didn't see the message property.
See https://nodejs.org/api/errors.html#class-error for a list of the fields that include:
- error.code
- error.message
- error.stack
To illustrate, copy the following line into your browser console, or run it as a NodeJS file.
console.log(JSON.stringify(new Error('huh')));
// output is: {}
But the field is there as shown by the following lines of code that display the message field.
console.log(JSON.stringify(new Error('huh'))); // {}
console.log((new Error('huh')).toString()); // Error: huh
console.log((new Error('huh')).message); // huh
I'm not sure what to search for to find this answer.
SO had the following but they were unrelated to my question:
For completeness, the MDN (browser) Error object is documented here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
UPDATE
This question was (rightfully) closed as a duplicate of Is it not possible to stringify an Error using JSON.stringify?.
The short answer to the question is:
The Error class doesn't have ".toJSON" method and the JSON.stringify() method's default way of obtaining properties to process does not include the message
field because the message field is not marked as enumerable
Reflect.getOwnPropertyDescriptor(new Error('huh'), 'message').enumerable
// returns false
Credit to @bogdanoff, ASDFGerte and @Jonathan Lonowski (for the duplicate answer)
To get all of the fields of the Error object you can use the following:
let err = new Error('huh');
console.log('stringify: ' + JSON.stringify(err, Object.getOwnPropertyNames(err)));
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error