語法
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 |
瀏覽器相容性
載入中…