尝试使用 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));
其他解决方法:
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3