"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does JSON.stringify Return an Empty Object When Serializing an Error?

Why Does JSON.stringify Return an Empty Object When Serializing an Error?

Published on 2025-01-21
Browse:689

Why Does JSON.stringify Return an Empty Object When Serializing an Error?

Is It Impossible to Stringify an Error Using JSON.stringify?

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:

  • Custom Error Objects: Create custom error objects with desired properties and serialize those.
  • Property Extraction: Extract specific error properties manually using error.stack and error.message.
Latest tutorial More>

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