如何解析window.onerror中的ReferenceError对象(第五个参数,在Google Chrome中实现)

时间:2014-05-30 16:55:48

标签: javascript json google-chrome

我正在使用

从控制台记录js错误
window.onerror = function (errorMsg, url, lineNumber, column, errorObj) 

想要JSON.stringify(),但是当我这样做时,第5个参数(在谷歌浏览器中实现) - 错误对象 - 用JSON表示,如:{}

enter image description here

如何对其进行字符串化?

1 个答案:

答案 0 :(得分:1)

stack是一个懒惰的评估属性。 (...)表示该值是通过getter计算的,仅在您显式访问变量时可用。

如果您希望对其进行合理的序列化,我建议使用自定义Error方法扩展toJSON的原型。然后,此方法将由ReferenceError继承,并在您向其传递错误实例时由JSON.stringify接收:

if (!Error.prototype.toJSON) {
    Error.prototype.toJSON = function() {
        return {
            name: this.name,
            message: this.message,
            stack: this.stack
        };
    };
}