DEV Community

Chris Cook
Chris Cook

Posted on • Originally published at zirkelc.dev

Stringify and Parse Errors in JavaScript

The Error object in JavaScript doesn't serialize to JSON with all its properties by default. That's because the Error.prototype (from which all error objects inherit) doesn't have a toJSON method defined. Consequently, if you attempt to serialize an error using JSON.stringify, you'll only get an empty object:

const error = new Error("My error message");
const jsonError = JSON.stringify(error);

//> prints "{}"
console.log(jsonError); 
Enter fullscreen mode Exit fullscreen mode

One way to capture the details of an error is by providing JSON.stringify with a replacer function or an array of property names to serialize. For an Error object, we're often interested in the message and stack properties. Here's how to stringify an Error object, capturing these properties:

const serializedError = JSON.stringify(error, 
  Object.getOwnPropertyNames(error)
);

//> prints "{"message":"My error message","stack":"..."}"
console.log(serializedError); 
Enter fullscreen mode Exit fullscreen mode

The challenge now is to reconstruct the error object from the serialized data. Simply parsing the JSON would give us a plain JavaScript object, but we want a real Error object:

const deserializedError = Object.assign(new Error(), 
  JSON.parse(serializedError)
);

//> prints "Error: My error message"
console.log(deserializedError); 
Enter fullscreen mode Exit fullscreen mode

First, JSON.parse transforms the JSON string back into a JavaScript object. Then, Object.assign is used to copy all properties from the parsed object to a new Error object.

This approach provides a simple way to serialize Error objects and then reconstruct them. However, it's important to note that there are other Error subclasses like TypeError, ReferenceError, or custom errors from libraries. Information about these specific error types will not be preserved when reconstructing the Error in this way.


I hope you found this post helpful. If you have any questions or comments, feel free to leave them below. If you'd like to connect with me, you can find me on LinkedIn or GitHub. Thanks for reading!

Top comments (0)