Home >Web Front-end >JS Tutorial >Why Does JSON.stringify Return an Empty Object When Serializing an Error?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-02 15:55:11877browse

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.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn