Stringify and Parse Errors in JavaScript

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); 

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); 

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); 

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!

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
how-to-hire-a-software-developer-for-your-web3-startup

How To Hire A Software Developer For Your Web3 Startup

Next Post
easy-to-implement-tactics-for-local-link-building-—-whiteboard-friday

Easy to Implement Tactics for Local Link Building — Whiteboard Friday

Related Posts