为什么错误不能字符串化

Why can Errors not be stringified?

本文关键字:字符串 不能 错误 为什么      更新时间:2023-09-26

为什么错误不能字符串化?

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

例如,当Date做一些更有用的事情时:

JSON.stringify(new Date()); // "2015-04-01T10:23:24.749Z"

JavaScript Error对象是不可枚举的。你可以很容易地验证这一点:

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

但是,您可以在错误Object:上定义自己的toJSON函数

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