Skip to content

Instantly share code, notes, and snippets.

@andresmatasuarez
Created March 4, 2015 18:19
Show Gist options
  • Save andresmatasuarez/c3e7380ee4fbecee3c3a to your computer and use it in GitHub Desktop.
Save andresmatasuarez/c3e7380ee4fbecee3c3a to your computer and use it in GitHub Desktop.
Javascript | Make Error objects JSON.stringify-able
// more info: https://stackoverflow.com/questions/18391212/is-it-not-possible-to-stringify-an-error-using-json-stringify
// Example:
// var error = new Error('testing');
// error.detail = 'foo bar';
// console.log(JSON.stringify(error)); // Prints {"message":"testing","detail":"foo bar"}
Object.defineProperty(Error.prototype, 'toJSON', {
value: function(){
var alt = {};
Object.getOwnPropertyNames(this).forEach(function(key){
alt[key] = this[key];
}, this);
return alt;
},
configurable: true
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment