Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs - JSON.stringify Error object

Tags:

node.js

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?

like image 327
user3828771 Avatar asked Dec 19 '22 12:12

user3828771


1 Answers

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.

like image 131
mscdex Avatar answered Jan 06 '23 11:01

mscdex