Attempting to serialize an error instance using JSON.stringify results in an empty object. This behavior arises from the hidden property descriptors of the error.
Why JSON.stringify Fails:
Property descriptors for error instances are set with enumerable: false, preventing their properties from being included in stringification.
Exploring Properties and Descriptors:
const error = new Error('sample message'); const propertyNames = Object.getOwnPropertyNames(error); propertyNames.forEach(property => console.log(property, Object.getOwnPropertyDescriptor(error, property)));
Output:
stack { get: [Function], set: [Function], enumerable: false, configurable: true } arguments { value: undefined, writable: true, enumerable: false, configurable: true } type { value: 'custom message', writable: true, enumerable: false, configurable: true } message { value: 'custom message', writable: true, enumerable: false, configurable: true }
Workaround Using Object.getOwnPropertyNames:
To include error properties in stringification, use JSON.stringify(err, Object.getOwnPropertyNames(err)). This provides access to non-enumerable properties.
const serializedError = JSON.stringify(error, Object.getOwnPropertyNames(error));
Additional Workarounds:
The above is the detailed content of Why Does JSON.stringify Return an Empty Object When Serializing an Error?. For more information, please follow other related articles on the PHP Chinese website!