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:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3