3

Why can Errors not be stringified?

JSON.stringify(new ReferenceError('foo')); // {}

When for example, Date does something more useful:

JSON.stringify(new Date()); // "2015-04-01T10:23:24.749Z"
Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • Have a look at [avascript-stringify-object-including-members-of-type-function][1] [1]: http://stackoverflow.com/questions/3685703/javascript-stringify-object-including-members-of-type-function – ran Apr 01 '15 at 10:27

1 Answers1

2

JavaScript Error objects are not enumerable. You can verify this easily:

new Error('Test').propertyIsEnumerable('message');
// -> false

You can however define your own toJSON function on the error Object:

Object.defineProperty(Error.prototype, 'toJSON', {
    value: function () {
        return {value: "Test"};
    },
    configurable: true
});

JSON.stringify(new Error());
-> "{value: "Test"}"
Jivings
  • 22,834
  • 6
  • 60
  • 101