【问题标题】:Destructuring error objects works in Chrome but not Firefox. What can be done?解构错误对象适用于 Chrome,但不适用于 Firefox。可以做什么?
【发布时间】:2020-07-22 00:06:22
【问题描述】:

想象下面这段代码:

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"
}

这有什么已知的原因吗?我能做些什么让它跨浏览器工作吗?

【问题讨论】:

  • 对象传播是 ES7 的一部分,并非在所有浏览器中都可用。请注意,它与数组扩展运算符不同。另外,你能分享一下你的 FF 版本吗?
  • @Rajesh 不正确.. 它在 es6 中可用,现在得到广泛支持
  • @xdeepakv 是数组传播。 ... 有 2 个实现,一个用于 ES6 中的 Array,另一个用于 ES7 中的 Object。它们看起来和感觉相同,但内部不同并且具有不同的兼容性。我会看看是否可以找到参考。 This 可能有帮助
  • 这不是这里的问题。问题是,如果描述为空,则不会打印。如果描述有价值,它正在工作..我测试过。
  • 问题是Error.captureStackTrace,在 Firefox 中无法正常工作。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

标签: javascript firefox error-handling cross-browser


【解决方案1】:

您的问题实际上与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' });
  }
})();

【讨论】:

  • 啊啊!我知道它一定是某处的红鲱鱼。谢谢
猜你喜欢
  • 1970-01-01
  • 2016-07-11
  • 1970-01-01
  • 1970-01-01
  • 2018-09-08
  • 2014-11-17
  • 2015-06-09
  • 2011-08-21
  • 1970-01-01
相关资源
最近更新 更多