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 {}
}
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.
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.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With