重现问题

我遇到了一个问题时,试图传递错误消息周围使用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删除所有函数,但随后意识到它也有一些奇怪的行为:

var error = new Error('simple error message');
JSON.stringify(error, function(key, value) {
    console.log(key === ''); // true (?)
    console.log(value === error); // true (?)
});

它似乎不像通常那样遍历对象,因此我不能检查键是否为函数并忽略它。

这个问题

有什么方法来stringify本机错误消息与JSON.stringify?如果不是,为什么会发生这种行为?

解决这个问题的方法

坚持使用简单的基于字符串的错误消息,或者创建个人错误对象,不要依赖于本机error对象。 拉取属性:JSON。Stringify({消息:错误。消息,堆栈:错误。栈})

更新

@Ray Toal在评论中建议我看一下属性描述符。现在很清楚为什么它不起作用了:

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。

公认的答案为这个问题提供了一个变通办法。


当前回答

既然没人说为什么,我来回答吧。

为什么是JSON。Stringify返回一个空对象?

> JSON.stringify(error);
'{}'

回答

在JSON.stringify()的文档中,

对于所有其他Object实例(包括Map、Set、WeakMap和WeakSet),只有它们的可枚举属性将被序列化。

和Error对象没有它的可枚举属性,这就是为什么它打印一个空对象。

其他回答

如果使用nodejs,则使用本地nodejs检查是更好的可靠方法。此外,您还可以指定将对象打印到无限深度。

打印稿的例子:

import { inspect }  from "util";

const myObject = new Error("This is error");
console.log(JSON.stringify(myObject)); // Will print {}
console.log(myObject); // Will print full error object
console.log(inspect(myObject, {depth: null})); // Same output as console.log plus it works as well for objects with many nested properties.

链接到文档,链接到示例用法。

并且在主题中也讨论了如何在Node.js的console.log()中获得完整的对象,而不是'[object]'?这里是堆栈溢出。

我已经扩展了这个答案:它是不可能stringify错误使用JSON.stringify?

serializeError.ts

export function serializeError(err: unknown) {
    return JSON.parse(JSON.stringify(err, Object.getOwnPropertyNames(err)))
}

我可以这样使用它:

import { serializeError } from '../helpers/serializeError'; // Change to your path

try {
    const res = await create(data);
    return { status: 201 };
} catch (err) {
    return { status: 400, error: serializeError(err) };
}

您还可以将那些不可枚举的属性重新定义为可枚举的。

Object.defineProperty(Error.prototype, 'message', {
    configurable: true,
    enumerable: true
});

也许还有堆栈属性。

既然没人说为什么,我来回答吧。

为什么是JSON。Stringify返回一个空对象?

> JSON.stringify(error);
'{}'

回答

在JSON.stringify()的文档中,

对于所有其他Object实例(包括Map、Set、WeakMap和WeakSet),只有它们的可枚举属性将被序列化。

和Error对象没有它的可枚举属性,这就是为什么它打印一个空对象。

我正在为日志追加器编写JSON格式,最后在这里尝试解决类似的问题。过了一段时间,我意识到我可以让Node来做这项工作:

const util = require("util");
...
return JSON.stringify(obj, (name, value) => {
    if (value instanceof Error) {
        return util.format(value);
    } else {
        return value;
    }
}