JavaScript/DOMException
DOMException
1. DOMExceptionとは
JavaScriptでDOM(Document Object Model)を操作する際、無効な操作や不正な値を使用すると、通常のエラーとは異なる DOMException が発生します。DOMExceptionは Error
オブジェクトの一種であり、ブラウザがDOM関連のエラーを検出したときに自動的にスローされます。
例えば、存在しない要素を操作しようとした場合や、読み取り専用のプロパティに値を代入しようとした場合に発生します。次のコードを見てみましょう。
// 存在しない要素を削除しようとするとエラーが発生 const element = document.getElementById("nonexistent"); element.remove();
このコードを実行すると、element
は null
であるため、remove()
メソッドを呼び出すことができず TypeError
が発生します。しかし、DOMException
は TypeError
とは異なり、DOM APIが直接スローする特別なエラーです。
2. DOMExceptionの基本構造
DOMException は Error
オブジェクトを継承しており、特定のプロパティを持ちます。
プロパティ名 | 説明 |
---|---|
name |
例外の種類を示す文字列。例えば NotFoundError など。 |
message |
エラーメッセージの詳細な説明。 |
code |
エラーの整数コード(非推奨、現在はほぼ使用されない)。 |
例えば、以下のコードは DOMException
の基本的な構造を確認するものです。
try { document.createElement("div").appendChild(document); } catch (e) { console.log(e.name); // HierarchyRequestError console.log(e.message); // ノードの追加が不適切であることを示すメッセージ }
この例では、document
オブジェクトを div
の子要素として追加しようとしたため、HierarchyRequestError
が発生します。
3. 代表的なDOMExceptionの種類
DOMException には多数の種類が存在し、それぞれ異なる状況で発生します。主なものを以下に示します。
例外名 | 発生条件 |
---|---|
IndexSizeError |
負のインデックスや範囲外のインデックスを指定した場合 |
HierarchyRequestError |
不正なノードの追加を試みた場合 |
WrongDocumentError |
別のドキュメントのノードを追加しようとした場合 |
NotFoundError |
存在しない要素やノードを操作しようとした場合 |
SecurityError |
クロスオリジン制約などのセキュリティ違反が発生した場合 |
QuotaExceededError |
localStorage などのストレージが上限を超えた場合 |
例えば、NotFoundError
は次のようなケースで発生します。
try { document.body.removeChild(document.getElementById("nonexistent")); } catch (e) { console.log(e.name); // NotFoundError }
このコードでは getElementById("nonexistent")
が null
を返すため、removeChild()
に渡せる要素が存在せず NotFoundError
が発生します。
4. 実際の発生例と対策
例1:不正なノードの追加
以下のコードでは、document
を div
の子要素として追加しようとしたため HierarchyRequestError
が発生します。
try { document.createElement("div").appendChild(document); } catch (e) { console.error(e.name); // HierarchyRequestError }
対策:適切なノードを追加するようにする。
const div = document.createElement("div"); const span = document.createElement("span"); div.appendChild(span); // 正常に動作
例2:ストレージ制限超過
localStorage
の保存容量を超えるデータを保存しようとすると QuotaExceededError
が発生します。
try { localStorage.setItem("largeData", "x".repeat(10**7)); } catch (e) { console.error(e.name); // QuotaExceededError }
対策:データのサイズを確認し、適切な制限を設ける。
5. DOMExceptionの適切なハンドリング
DOMException が発生する可能性があるコードでは、try...catch
を使用して適切に処理することが重要です。
例1:instanceof
による判別
try { document.body.removeChild(document.getElementById("nonexistent")); } catch (e) { if (e instanceof DOMException) { console.error("DOMException 発生: " + e.name); } else { console.error("その他のエラー: " + e.message); } }
例2:エラーの種類に応じた処理
try { document.body.removeChild(document.getElementById("nonexistent")); } catch (e) { switch (e.name) { case "NotFoundError": console.warn("要素が見つかりませんでした。"); break; case "QuotaExceededError": console.warn("ストレージの容量制限を超えています。"); break; default: console.error("予期しないエラー: " + e.message); } }
6. まとめ
DOMException は、DOM操作時に発生する特別なエラーであり、適切に処理することが重要です。代表的なエラーには NotFoundError
や HierarchyRequestError
などがあり、それぞれ発生条件が異なります。安全なDOM操作を行うためには、
try...catch
を活用して適切に例外処理を行うinstanceof DOMException
やname
プロパティを使ってエラーを判別する- 事前に入力や操作を検証し、不要なエラーを防ぐ
といった対策が求められます。適切なエラーハンドリングを学び、安全なJavaScript開発を心がけましょう。
附録
静的プロパティ
- DOMException.ABORT_ERR
- DOMException.DATA_CLONE_ERR
- DOMException.DOMSTRING_SIZE_ERR
- DOMException.HIERARCHY_REQUEST_ERR
- DOMException.INDEX_SIZE_ERR
- DOMException.INUSE_ATTRIBUTE_ERR
- DOMException.INVALID_ACCESS_ERR
- DOMException.INVALID_CHARACTER_ERR
- DOMException.INVALID_MODIFICATION_ERR
- DOMException.INVALID_NODE_TYPE_ERR
- DOMException.INVALID_STATE_ERR
- DOMException.NAMESPACE_ERR
- DOMException.NETWORK_ERR
- DOMException.NOT_FOUND_ERR
- DOMException.NOT_SUPPORTED_ERR
- DOMException.NO_DATA_ALLOWED_ERR
- DOMException.NO_MODIFICATION_ALLOWED_ERR
- DOMException.QUOTA_EXCEEDED_ERR
- DOMException.SECURITY_ERR
- DOMException.SYNTAX_ERR
- DOMException.TIMEOUT_ERR
- DOMException.TYPE_MISMATCH_ERR
- DOMException.URL_MISMATCH_ERR
- DOMException.VALIDATION_ERR
- DOMException.WRONG_DOCUMENT_ERR
- DOMException.arguments
- DOMException.caller
- DOMException.length
- DOMException.name
- DOMException.prototype
静的アクセサ
静的メソッド
DOMExceptionのインスタンスプロパティ
- DOMException.prototype.ABORT_ERR
- DOMException.prototype.DATA_CLONE_ERR
- DOMException.prototype.DOMSTRING_SIZE_ERR
- DOMException.prototype.HIERARCHY_REQUEST_ERR
- DOMException.prototype.INDEX_SIZE_ERR
- DOMException.prototype.INUSE_ATTRIBUTE_ERR
- DOMException.prototype.INVALID_ACCESS_ERR
- DOMException.prototype.INVALID_CHARACTER_ERR
- DOMException.prototype.INVALID_MODIFICATION_ERR
- DOMException.prototype.INVALID_NODE_TYPE_ERR
- DOMException.prototype.INVALID_STATE_ERR
- DOMException.prototype.NAMESPACE_ERR
- DOMException.prototype.NETWORK_ERR
- DOMException.prototype.NOT_FOUND_ERR
- DOMException.prototype.NOT_SUPPORTED_ERR
- DOMException.prototype.NO_DATA_ALLOWED_ERR
- DOMException.prototype.NO_MODIFICATION_ALLOWED_ERR
- DOMException.prototype.QUOTA_EXCEEDED_ERR
- DOMException.prototype.SECURITY_ERR
- DOMException.prototype.SYNTAX_ERR
- DOMException.prototype.TIMEOUT_ERR
- DOMException.prototype.TYPE_MISMATCH_ERR
- DOMException.prototype.URL_MISMATCH_ERR
- DOMException.prototype.VALIDATION_ERR
- DOMException.prototype.WRONG_DOCUMENT_ERR
- DOMException.prototype [ Symbol.toStringTag ]