语法
js
Error.isError(value)
参数
value-
待检查的值。
返回值
如果 value 是 Error 对象,则返回 true;否则返回 false。
描述
Error.isError() 检查传入的值是否是 Error 对象。它通过执行对由 Error() 构造函数初始化的私有字段进行品牌检查来实现。这与 Array.isArray() 使用的机制相同,而后者又与 in 运算符使用的机制类似。
它是 instanceof Error 的更健壮的替代方案,因为它避免了误报和漏报。
Error.isError()会拒绝实际不是Error实例的值,即使它们在其原型链中有Error.prototype—instanceof Error会接受这些值,因为它会检查原型链。Error.isError()接受在另一个 realm 中构造的Error对象 —instanceof Error对于这些对象返回false,因为Error构造函数的标识在不同的 realm 中是不同的。
Error.isError() 对 DOMException 实例返回 true。这是因为,尽管 DOMException 未被指定为 Error 的真正子类(Error 构造函数不是 DOMException 构造函数的原型),但 DOMException 在所有品牌检查目的上仍然表现得像 Error。
示例
使用 Error.isError()
js
// all following calls return true
Error.isError(new Error());
Error.isError(new TypeError());
Error.isError(new DOMException());
try {
1 + 1n;
} catch (e) {
console.log(Error.isError(e)); // The operation threw a TypeError, so this returns true
}
// all following calls return false
Error.isError();
Error.isError({});
Error.isError(null);
Error.isError(undefined);
Error.isError(17);
Error.isError("Error");
Error.isError(true);
Error.isError(false);
// This is not an error, because the object does not have the private field
// initialized by the Error constructor
Error.isError({ __proto__: Error.prototype });
instanceof 与 Error.isError() 对比
在检查 Error 实例时,首选 Error.isError() 而不是 instanceof,因为它可以在不同 realm 之间工作。
js
const iframe = document.createElement("iframe");
document.body.appendChild(iframe);
const xError = window.frames[window.frames.length - 1].Error;
const error = new xError();
// Correctly checking for Error
Error.isError(error); // true
// The prototype of error is xError.prototype, which is a
// different object from Error.prototype
error instanceof Error; // false
规范化捕获的错误
您可以使用 Error.isError() 来检测捕获的值是否是错误,并将其规范化为错误对象。
js
try {
throw "Oops; this is not an Error object";
} catch (e) {
if (!Error.isError(e)) {
e = new Error(e);
}
console.error(e.message);
}
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-error.iserror |
浏览器兼容性
加载中…