对象传播错误导致没有消息属性 [英] Object spread an Error results in no message property

查看:96
本文介绍了对象传播错误导致没有消息属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试传播错误,以便我可以在不影响原始错误的情况下更改错误.

I'm trying to spread an Error so that I can alter the error without affecting the original error.

const error = new Error('Error test');

const freeError = {...error};
console.log(error, freeError);

但是输出是一个空对象{}.我希望freeError至少具有邮件属性,但没有.

But the output is an empty object {}. I'm expecting the freeError have at least a message property, but there is none.

这是JavaScript功能的一部分,还是我的代码或引擎有问题?

Is this a part of JavaScript feature or is there something wrong with my code or engine?

我知道一种解决此问题的方法,但这需要额外的工作{...error, message: error.message}.所以,是的,我需要做的是澄清,这样我就可以确定自己没有遗漏任何东西.谢谢.

I know a way to fix this, but it requires an extra work {...error, message: error.message}. So, yeah, all I need is a clarification so that I can be sure that I am not missing something. Thank you.

推荐答案

对象传播仅复制可枚举的自己的属性,并且至少在某些环境中,message不是可枚举的自己的属性.

Object spread only copies enumerable own properties, and at least in some environments, the message is not an enumerable own property.

在Chrome中,它是不可枚举的自有属性,在Firefox中,它是Error.prototype的属性:

In Chrome, it's a non-enumerable own property, and in Firefox, it's a property of Error.prototype:

const error = new Error('Error test');

// Chrome logs an object (including "enumerable": false,)
console.log(Object.getOwnPropertyDescriptor(error, 'message'));

// Firefox logs an object (including "enumerable": false,)
console.log(Object.getOwnPropertyDescriptor(Object.getPrototypeOf(error), 'message'));

这取决于实现.我会手动提取您需要的所有属性:

It's implementation-dependent. I'd manually extract all properties you need:

const error = new Error('Error test');
const { message, stack } = error;
const freeError = { message, stack };
console.log(freeError);

这篇关于对象传播错误导致没有消息属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆