”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 为什么 JSON.stringify 在序列化错误时返回空对象?

为什么 JSON.stringify 在序列化错误时返回空对象?

发布于2025-01-21
浏览:512

Why Does JSON.stringify Return an Empty Object When Serializing an Error?

是否不可能使用 JSON.stringify 字符串化错误?

尝试使用 JSON.stringify 序列化错误实例会导致空对象。此行为是由错误的隐藏属性描述符引起的。

为什么 JSON.stringify 失败:

错误实例的属性描述符设置为 enumerable: false,防止它们属性不包含在字符串化中。

探索属性和描述符:

const error = new Error('sample message');
const propertyNames = Object.getOwnPropertyNames(error);
propertyNames.forEach(property => console.log(property, Object.getOwnPropertyDescriptor(error, property)));

输出:

stack { get: [Function], set: [Function], enumerable: false, configurable: true }
arguments { value: undefined, writable: true, enumerable: false, configurable: true }
type { value: 'custom message', writable: true, enumerable: false, configurable: true }
message { value: 'custom message', writable: true, enumerable: false, configurable: true }

使用 Object.getOwnPropertyNames 的解决方法:

将错误属性包含在字符串化,使用 JSON.stringify(err, Object.getOwnPropertyNames(err))。这提供了对不可枚举属性的访问。

const serializedError = JSON.stringify(error, Object.getOwnPropertyNames(error));

其他解决方法:

  • 自定义错误对象: 创建具有所需属性的自定义错误对象并序列化这些。
  • 属性提取:使用 error.stack 和 error.message 手动提取特定错误属性。
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3