4

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?

user3828771
  • 1,603
  • 3
  • 14
  • 14

1 Answers1

12

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.

mscdex
  • 104,356
  • 15
  • 192
  • 153