Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JSON.stringify on TypeError return an empty object [duplicate]

I'm using node 4.2, and I'm catching an error and using JSON.stringify on it. For most objects, this works fine. But when a [TypeError: callback is not a function] is thrown, it returns an empty object. if I console.log it directly, it works fine.

Mozilla's page says:

Boolean, Number, and String objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics.

try {
    ...
} catch (err) {
    console.log('error: ' + JSON.stringify(err)) // outputs {}
}
like image 561
Hyo Byun Avatar asked Dec 15 '15 19:12

Hyo Byun


People also ask

Can JSON Stringify throw an error?

Error Handling parse(), JSON. stringify() may throw errors, so it should be wrapped in a try catch statement. The function throws a TypeError in two contexts: if a circular reference occurs in the Javascript object or if the Javascript object contains a BigInt. A replacer cannot catch or change these errors.

What is the return type of JSON Stringify?

If you return a number, string, boolean, or null , that value is directly serialized and used as the property's value. (Returning a BigInt will throw as well.) If you return a Function , Symbol , or undefined , the property is not included in the output.

What happens when you JSON Stringify a string?

The JSON. stringify() method in Javascript is used to create a JSON string out of it. While developing an application using JavaScript, many times it is needed to serialize the data to strings for storing the data into a database or for sending the data to an API or web server.

Does JSON Stringify work on objects?

JSON. stringify() will encode values that JSON supports. Objects with values that can be objects, arrays, strings, numbers and booleans. Anything else will be ignored or throw errors.


1 Answers

When you use stringify on a TypeError, you're stringifying an object with no enumerable properties.

So if you do

var typeError = new TypeError("hey")
for(var prop in typeError) {
  console.log(prop) // this does not run
}

When you log using console.log, you're using valueOf, so

var typeError = new TypeError("hey")
typeError.valueOf()  // TypeError: hey(…)

Also, an error knows how to turn itself into a string, so this works too:

var typeError = new TypeError("hey")
typeError.toString() // "TypeError: hey"

If you want to log the properties of an object you can't see using a normal log, you can console.dir the object.

When you do it on the typeError, you'll see that it has a message property:

enter image description here

like image 130
nicosantangelo Avatar answered Oct 21 '22 01:10

nicosantangelo