3 回答

TA貢獻(xiàn)1934條經(jīng)驗(yàn) 獲得超2個(gè)贊
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
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));

TA貢獻(xiàn)1844條經(jīng)驗(yàn) 獲得超8個(gè)贊
var stringifyError = function(err, filter, space) { var plainObject = {}; Object.getOwnPropertyNames(err).forEach(function(key) { plainObject[key] = err[key]; }); return JSON.stringify(plainObject, filter, space);};var error = new Error('testing');error.detail = 'foo bar';console.log(stringifyError(error, null, '\t'));

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超2個(gè)贊
JSON.stringify
> JSON.stringify(error);'{}'
回答
對(duì)于所有其他對(duì)象實(shí)例(包括Map、Set、WeakMap和WeakSet),只有它們的可枚舉屬性才會(huì)被序列化。
Error
添加回答
舉報(bào)