【发布时间】:2013-08-25 19:39:49
【问题描述】:
重现问题
我在尝试使用 Web 套接字传递错误消息时遇到了问题。我可以使用JSON.stringify 复制我面临的问题以迎合更广泛的受众:
// node v0.10.15
> var error = new Error('simple error message');
undefined
> error
[Error: simple error message]
> Object.getOwnPropertyNames(error);
[ 'stack', 'arguments', 'type', 'message' ]
> JSON.stringify(error);
'{}'
问题是我最终得到了一个空对象。
我尝试过的
浏览器
我首先尝试离开 node.js 并在各种浏览器中运行它。 Chrome 28 版给了我同样的结果,有趣的是,Firefox 至少做了一次尝试,但遗漏了这条消息:
>>> JSON.stringify(error); // Firebug, Firefox 23
{"fileName":"debug eval code","lineNumber":1,"stack":"@debug eval code:1\n"}
替换函数
然后我查看了Error.prototype。说明原型中包含toString、toSource等方法。知道函数不能被字符串化,我在调用 JSON.stringify 以删除所有函数时包含了replacer function,但后来意识到它也有一些奇怪的行为:
var error = new Error('simple error message');
JSON.stringify(error, function(key, value) {
console.log(key === ''); // true (?)
console.log(value === error); // true (?)
});
它似乎没有像往常那样循环遍历对象,因此我无法检查键是否是函数并忽略它。
问题
有没有办法用JSON.stringify 对原生错误消息进行字符串化?如果不是,为什么会出现这种情况?
解决方法
- 坚持使用简单的基于字符串的错误消息,或创建个人错误对象,不要依赖本机 Error 对象。
- 拉属性:
JSON.stringify({ message: error.message, stack: error.stack })
更新
@Ray Toal 在评论中建议我看看property descriptors。现在很清楚为什么它不起作用:
var error = new Error('simple error message');
var propertyNames = Object.getOwnPropertyNames(error);
var descriptor;
for (var property, i = 0, len = propertyNames.length; i < len; ++i) {
property = propertyNames[i];
descriptor = Object.getOwnPropertyDescriptor(error, property);
console.log(property, descriptor);
}
输出:
stack { get: [Function],
set: [Function],
enumerable: false,
configurable: true }
arguments { value: undefined,
writable: true,
enumerable: false,
configurable: true }
type { value: undefined,
writable: true,
enumerable: false,
configurable: true }
message { value: 'simple error message',
writable: true,
enumerable: false,
configurable: true }
密钥:enumerable: false。
已接受的答案提供了解决此问题的方法。
【问题讨论】:
-
您检查过错误对象中属性的属性描述符吗?
-
我的问题是“为什么”,我发现答案在问题的底部。为您自己的问题发布答案并没有错,而且您可能会以这种方式获得更多的信任。 :-)
-
serialize-error包会为您处理这个问题:npmjs.com/package/serialize-error
标签: javascript json node.js error-handling