Categories
JavaScript Answers

How to stringify an Error using JSON.stringify?

Spread the love

Sometimes, we want to stringify an Error using JSON.stringify.

In this article, we’ll look at how to stringify an Error using JSON.stringify.

How to stringify an Error using JSON.stringify?

To stringify an Error using JSON.stringify, we can call inspect.

For instance, we write

import {
  inspect
} from "util";

const myObject = new Error("This is error");
console.log(inspect(myObject, {
  depth: null
}));

to call inspect with the myObject error object.

The 2nd argument is an object with depth set to null, which lets us stringify all nested properties in the myObject error object.

Conclusion

To stringify an Error using JSON.stringify, we can call inspect.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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