How to stringify an Error using JSON.stringify?

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.