想象一下下面的代码:
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] 删除。
我来说两句