Is it not possible to stringify an Error using JSON.stringify?
JSON.stringify()
fails to stringify Error
objects due to their non-enumerable properties. Use the following workaround:
Object.getOwnPropertyNames()
ensures a complete serialization of the Error
object by grabbing all properties.
Understanding error serialization
The hurdle to stringify an Error object stems from the non-enumerable properties of an error object which JSON.stringify()
overlooks. Here are several strategies to handle this issue effectively.
Enhancing error serialization with toJSON
One approach is adding a toJSON
method to Error.prototype
, to prepare Error
objects for serialization:
With this enhancement, Error
objects now are exposed to JSON.stringify
and get successfully serialized.
Using a replacer function
Alternatively, we can customize the serialization with a replacer function in JSON.stringify
:
This technique bypasses the non-enumerability of Error
properties, enabling a wholistic serialization.
Creating enriched error objects
Personalized error objects offer an avenue for adding enumerated properties. These custom errors can combine useful details right out of the box when stringified:
Utilizing external libraries
In case you prefer a ready-made solution, the serialize-error
npm package offers serialization for error objects right off the shelf:
Visualization
A simple JSON.stringify()
call seems to comprehensively transform complex objects into JSON strings:
But when we attempt the same process with an Error
object:
It's a head-scratcher, akin to this equation:
The details (stack trace, message) are invisible to the typical operation by JSON.stringify
, as it misses the non-enumerable properties.
Unraveling the ghost properties
The core of the issue involves enumerable vs non-enumerable properties. Error properties are non-enumerable by design, hypothetically to avoid unwittingly revealing sensitive data.
Applying selective serialization
It may be the case that you only wish for particular properties to be serialized. Here, a custom filter function can deliver granular control:
This function only stringifies the name
, message
, and stack
properties, quietly disregarding incidental or sensitive records.
Ensuring serialization sanity
Before deploying any serialization strategy, it's crucial to test extensively. Verification of your stringifyError
functions and the richness of your error logs forms the cornerstone of tough and reliable error handling.
Was this article helpful?