javascript - 解构错误对象在 Chrome 中有效,但在 Firefox 中无效。可以做什么?

标签 javascript firefox error-handling cross-browser

想象一下下面的代码:

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 中,它只是忽略原型(prototype)扩展中添加的属性:

[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' });
  }
})();

关于javascript - 解构错误对象在 Chrome 中有效,但在 Firefox 中无效。可以做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61119995/

相关文章:

javascript - express.js req.body 在中间件中未定义

javascript - 使用 QWebElements 填写网页表单

javascript - Firefox 无法正确显示图像 (CSS + HTML)

Javascript 函数无法跨浏览器工作。

css - margin-left 在 Firefox 中不起作用

c# - 连接数据库时出错

javascript - google.load 正在加载导致版本控制问题的旧版本 jquery

.net - 错误记录类中最好的异常处理策略是什么?

c - 如何修复在 C 上显示段错误的代码?

javascript - 将 Chart JS 2 上的条形图扩展为一种新型图表