I'm trying to convert Error object
to JSON. However, the Error message
seems to be lost.
try{
require('someModule');
}catch(error){
console.log(JSON.stringify(error)) //{"code":"MODULE_NOT_FOUND"}
}
Did I do anything wrong? How can I fix it?
The issue has to do with the fact that some of the properties set on Errors are configured as non-enumerable.
Here's something you can use to properly stringify Error objects, it sets a toJSON()
method that JSON.stringify()
looks for when converting an object:
var config = {
configurable: true,
value: function() {
var alt = {};
var storeKey = function(key) {
alt[key] = this[key];
};
Object.getOwnPropertyNames(this).forEach(storeKey, this);
return alt;
}
};
Object.defineProperty(Error.prototype, 'toJSON', config);
Then just use JSON.stringify()
as normal.
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