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?

2
  • It's not the error message being lost. What you just put in the comment is the full error object. Commented Jul 28, 2014 at 15:18
  • Where is the error message? Commented Jul 28, 2014 at 15:19

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your explanation. By the way, is var storeKey = function(key) a typo?
@user3828771 Code is fixed now.
It's important to note that this breaks mongodb client: jira.mongodb.org/browse/NODE-554

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.