这是不可能的stringify错误使用json.stringify?

CommunityJay Querie提出了一个问题:Is it not possible to stringify an Error using JSON.stringify?,或许与您遇到的问题类似。

回答者Jonathan Lonowski给出了该问题的处理方式:

You can define a Error.prototype.toJSONto retrieve a plain Objectrepresenting the 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"}

Using Object.defineProperty()adds toJSONwithout it being an enumerableproperty itself.


Regarding modifying Error.prototype, while toJSON()may not be defined for Errors specifically, the method is still standardizedfor objects in general (ref: step 3). So, the risk of collisions or conflicts is minimal.

Though, to still avoid it completely, JSON.stringify()'s replacerparametercan be used instead:

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));

希望本文对你有帮助,欢迎支持JavaScript中文网

原文链接:stackoverflow.com

上一篇:JavaScript闭包是如何垃圾收集的
下一篇:jasmine.js比较数组

相关推荐

官方社区

扫码加入 JavaScript 社区