想象一下下面的代码:
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/