解构错误对象在Chrome中有效,但在Firefox中无效。该怎么办?

马特·弗莱彻

想象一下下面的代码:

class FakeError extends Error {
  constructor(message, opts = {}) {
    super(message);
    const { description = null } = opts;
    this.description = description;
    Error.captureStackTrace(this, this.constructor);
  }
}

(() => {
  try {
    throw new FakeError('Test', { description: 'This is a test' });
  }
  catch (error) {
    console.log({ ...error, test: 'test' });
  }
})();

在Chrome中,这带有所需的响应,即将错误视为正常对象对待:

[object Object] {
  description: "This is a test",
  test: "test"
}

但是,在Firefox中,它只是忽略了原型扩展中添加的属性:

[object Object] {
  test: "test"
}

是否有已知原因?我可以做些什么使它跨浏览器工作?

德克尔

您的问题实际上与有关Error.captureStackTrace,这不是标准内容,并非在所有浏览器中都可用。

检查修复:

class FakeError extends Error {
  constructor(message, opts = {}) {
    super(message);
    const { description = null } = opts;
    this.description = description;
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, this.constructor);
    }
  }
}

(() => {
  try {
    throw new FakeError('Test', { description: 'This is a test' });
  }
  catch (error) {
    console.log({ ...error, test: 'test' });
  }
})();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

内联在 CSS 中的 SVG 在 Chrome/Edge 中有效,但在 Firefox 中无效

伪元素在 Firefox 中有效,但在 Chrome 中无效,为什么?

Selenium 测试用例在 Firefox 中有效,但在 Chrome 中无效 - Headless Setup

jQuery Click 功能在 Firefox 中有效,但在 Chrome/Safari 中无效

位置粘性在 Firefox 中有效,在 Chrome 中无效

应用于音频元素的样式在 firefox 和 safari 中有效,但在 chrome 中无效

为什么该程序在Python 2.7.6中有效,但在Python 3中无效?

该示例在js小提琴中有效,但在自制页面中无效

元素上的過渡在 Chrome 中有效,但在 Firefox 中無效

代码在Firefox Scratchpad中有效,但在代码中无效

使用 webdriver (C#) 上传文件在 Firefox 中有效,但在 IE 中无效

对象!= nil在Beta 5中有效,但在Beta 6中无效吗?

解构(扩展运算符)在 React JSX 中有效,但在外部无效?

高度:100%在Chrome中有效,但在Safari中无效

为什么我的API调用在chrome中有效,但在我的代码中无效?

简单的代码在 Chrome DevTool 中有效,但在 TamperMonkey 中无效

如果nginx错误日志中有可疑条目,该怎么办

orphanRemoval在PostgreSQL中有效,但在hsqldb中无效

函数在查询中有效,但在约束中无效

Scrapy 在 shell 中有效,但在代码中无效

代码在终端中有效,但在脚本中无效

WritePrivateProfileString 在 main 中有效但在函数中无效

图形在Chrome上有效,但在Firefox上无效

当按钮单击对某些数据集有效而对另一些数据集无效时该怎么办?

window.open在Firefox中有效,但在IE或Chrome中不起作用

日期构造函数在IE中返回NaN,但在Firefox和Chrome中有效

单一测试在PhantomJS中失败,但在Chrome和Firefox中有效

我的专栏文章将在Firefox / Safari中换行,但在Chrome中有效

Rmarkdown flexdashboard值框在Chrome或IE中无法正确呈现(但在FireFox中有效)