JSON.stringify() returns empty object.

json_stringify

We often encounter this issue, that while trying to stringify the error object, it returns the empty object. Many developers have below questions in their mind.

Q. JSON.stringify is not able to return any value for error objects, neither throwing any error why?
Q. JSON.stringify is not working properly for error object why?
Q. JSON.stringify is not able to return any value for error objects in catch block why?

We will try to explain it in this article, it will help everyone to understand the reason behind this behaviour of JSON.stringyfy.

What is JSON.stringify ?

JSON.stringify is a javascript function which converts a javascript object in to a json string. This method is commonly used to send data from the client side to a web server in a string format.

Ex: JSON.stringify(obj);

How JSON.stringify works Ideally ?

When we call: JSON.stringify(obj);

It attempts to convert the enumerable own properties of the object into a JSON string.

Ex: const obj = {
name: “alex”,
age: 20
};

console.log(JSON.stringify(obj)); // {“name”:”alex”,”age”:20}

So its work fine, but this behavior depends on enumerable properties. so if we will try the same with non-enumerable properties: the behaviour of JSON.stringify is changing.

So what’s the issue with error object, are they non-enumerable? let’s understand this.

Problem with Error Objects:

Error objects in JavaScript have non-enumerable properties. so properties of error object like message, name, and stack are non-enumerable by design. so while trying to stringify the error object, we get {} because there’s nothing enumerable to stringify!

What is a Non-Enumerable Property?

A property is non-enumerable if it won’t show up during a for...in loop or Object.keys() call. For Ex:

onst obj = {};
Object.defineProperty(obj, 'hidden', {
  value: 'secret',
  enumerable: false
});

console.log(JSON.stringify(obj)); // {}

This is exactly what happens with the default Error object. so the Error object’s properties like message, name, and stack are non-enumerable, and JSON.stringify() ignores them.

Solution:

How to properly serialize an error in Node.js?

We can either manually extract the properties:

try {
  throw new Error("Something went wrong!");
} catch (err) {
  const errorDetails = {
    message: err.message,
    name: err.name,
    stack: err.stack,
  };
  console.log(JSON.stringify(errorDetails));
}

Or define a helper function:

function serializeError(error) {
  return {
    name: error.name,
    message: error.message,
    stack: error.stack,
    ...(error.code && { code: error.code }),
    ...(error.cause && { cause: error.cause }),
  };
}

That’s it. it should work fine now.

I hope this helps everyone!, Feel free to comment for any suggestion or update to the article

Leave a Reply

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

Back To Top