解构错误对象在 Chrome 中有效,但在 Firefox 中无效。可以做什么?
Destructuring error objects works in Chrome but not Firefox. What can be done?
想象一下下面这段代码:
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' });
}
})();
想象一下下面这段代码:
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' });
}
})();