您可以定义
Error.prototype.toJSON来检索
Object表示的纯文本
Error:
if (!('toJSON' in Error.prototype))Object.defineProperty(Error.prototype, 'toJSON', { value: function () { var alt = {}; Object.getOwnPropertyNames(this).forEach(function (key) { alt[key] = this[key]; }, this); return alt; }, configurable: true, writable: true});var error = new Error('testing');error.detail = 'foo bar';console.log(JSON.stringify(error));// {"message":"testing","detail":"foo bar"}使用
Object.defineProperty()添加
toJSON而不将其
enumerable本身作为属性。
关于修改
Error.prototype,虽然
toJSON()可能没有
Error专门针对它进行修改,但是该方法通常仍针对对象进行了标准化(参见:步骤3)。因此,冲突或冲突的风险很小。
不过,为了完全避免它,可以使用
JSON.stringify()的
replacer参数代替:
function replaceErrors(key, value) { if (value instanceof Error) { var error = {}; Object.getOwnPropertyNames(value).forEach(function (key) { error[key] = value[key]; }); return error; } return value;}var error = new Error('testing');error.detail = 'foo bar';console.log(JSON.stringify(error, replaceErrors));


