JS/TSに組み込まれているエラークラス一覧
// ── JavaScriptの組み込みエラー型 ────────────────────────
// 全て Error を継承しており、instanceof で種類を判別できる
// TypeError: 型が期待と違う場合
try {
(null as any).toString(); // null のメソッドを呼ぶ
} catch (e) {
console.log(e instanceof TypeError, (e as Error).message);
// true, "Cannot read properties of null"
}
// RangeError: 数値が有効範囲外の場合
try {
new Array(-1); // 配列のサイズにマイナスを指定
} catch (e) {
console.log(e instanceof RangeError); // true
}
// ReferenceError: 定義されていない変数を参照した場合
try {
eval('undeclaredVariable');
} catch (e) {
console.log(e instanceof ReferenceError); // true
}
// SyntaxError: JSON.parse でよく遭遇する
try {
JSON.parse('{ invalid json }');
} catch (e) {
console.log(e instanceof SyntaxError); // true
}
// URIError: decodeURI に不正な URI を渡した場合
try {
decodeURI('%'); // 不正なパーセントエンコード
} catch (e) {
console.log(e instanceof URIError); // true
}各エラータイプをinstanceofで判別できる。TypeScriptではcatch節のerrはunknown型なので必ずinstanceofで絞り込む。