0
# Error Handling
1
2
Comprehensive error reporting system with DOM-standard exceptions and parsing-specific error types for robust XML processing applications.
3
4
## Capabilities
5
6
### DOMException Class
7
8
Standard DOM exception class for DOM manipulation errors.
9
10
```javascript { .api }
11
/**
12
* DOM-specific exception class following W3C standards
13
* Thrown by DOM operations that encounter exceptional conditions
14
*/
15
class DOMException extends Error {
16
constructor(message?: string, name?: string);
17
constructor(code?: number, message?: string);
18
19
readonly name: string; // Exception name
20
readonly code: number; // Numeric exception code (0 for modern names)
21
22
// Static exception codes (legacy)
23
static readonly INDEX_SIZE_ERR: 1;
24
static readonly DOMSTRING_SIZE_ERR: 2;
25
static readonly HIERARCHY_REQUEST_ERR: 3;
26
static readonly WRONG_DOCUMENT_ERR: 4;
27
static readonly INVALID_CHARACTER_ERR: 5;
28
static readonly NO_DATA_ALLOWED_ERR: 6;
29
static readonly NO_MODIFICATION_ALLOWED_ERR: 7;
30
static readonly NOT_FOUND_ERR: 8;
31
static readonly NOT_SUPPORTED_ERR: 9;
32
static readonly INUSE_ATTRIBUTE_ERR: 10;
33
static readonly INVALID_STATE_ERR: 11;
34
static readonly SYNTAX_ERR: 12;
35
static readonly INVALID_MODIFICATION_ERR: 13;
36
static readonly NAMESPACE_ERR: 14;
37
static readonly INVALID_ACCESS_ERR: 15;
38
static readonly VALIDATION_ERR: 16;
39
static readonly TYPE_MISMATCH_ERR: 17;
40
static readonly SECURITY_ERR: 18;
41
static readonly NETWORK_ERR: 19;
42
static readonly ABORT_ERR: 20;
43
static readonly URL_MISMATCH_ERR: 21;
44
static readonly QUOTA_EXCEEDED_ERR: 22;
45
static readonly TIMEOUT_ERR: 23;
46
static readonly INVALID_NODE_TYPE_ERR: 24;
47
static readonly DATA_CLONE_ERR: 25;
48
}
49
```
50
51
**Usage Examples:**
52
53
```javascript
54
const { DOMParser, DOMException } = require('@xmldom/xmldom');
55
56
try {
57
const doc = parser.parseFromString('<root></root>', 'text/xml');
58
const root = doc.documentElement;
59
60
// This might throw a DOMException
61
root.removeChild(doc.createElement('nonexistent'));
62
} catch (error) {
63
if (error instanceof DOMException) {
64
console.log(`DOM Error: ${error.name} (${error.code}): ${error.message}`);
65
66
switch (error.name) {
67
case 'NotFoundError':
68
console.log('Attempted to remove non-existent child');
69
break;
70
case 'HierarchyRequestError':
71
console.log('Invalid tree modification');
72
break;
73
case 'WrongDocumentError':
74
console.log('Node belongs to different document');
75
break;
76
}
77
}
78
}
79
```
80
81
### ParseError Class
82
83
Specialized error class for XML parsing failures.
84
85
```javascript { .api }
86
/**
87
* Error thrown during XML parsing when fatal errors occur
88
* Provides additional context about parse location and cause
89
*/
90
class ParseError extends Error {
91
constructor(message: string, locator?: any, cause?: Error);
92
93
readonly message: string;
94
readonly locator?: any; // Location information if available
95
readonly cause?: Error; // Underlying cause if chained
96
}
97
```
98
99
**Usage Examples:**
100
101
```javascript
102
const { DOMParser, ParseError } = require('@xmldom/xmldom');
103
104
const parser = new DOMParser({
105
onError: (level, message, context) => {
106
if (level === 'fatalError') {
107
throw new ParseError(`Fatal parsing error: ${message}`, context);
108
}
109
}
110
});
111
112
try {
113
const doc = parser.parseFromString('<invalid><xml>', 'text/xml');
114
} catch (error) {
115
if (error instanceof ParseError) {
116
console.log(`Parse Error: ${error.message}`);
117
if (error.locator) {
118
console.log(`Location: line ${error.locator.lineNumber}, column ${error.locator.columnNumber}`);
119
}
120
}
121
}
122
```
123
124
### Exception Names and Codes
125
126
```javascript { .api }
127
/**
128
* Standard DOM exception names
129
*/
130
const DOMExceptionName = {
131
Error: 'Error',
132
IndexSizeError: 'IndexSizeError', // deprecated
133
DomstringSizeError: 'DomstringSizeError', // deprecated
134
HierarchyRequestError: 'HierarchyRequestError',
135
WrongDocumentError: 'WrongDocumentError',
136
InvalidCharacterError: 'InvalidCharacterError',
137
NoDataAllowedError: 'NoDataAllowedError', // deprecated
138
NoModificationAllowedError: 'NoModificationAllowedError',
139
NotFoundError: 'NotFoundError',
140
NotSupportedError: 'NotSupportedError',
141
InUseAttributeError: 'InUseAttributeError',
142
InvalidStateError: 'InvalidStateError',
143
SyntaxError: 'SyntaxError',
144
InvalidModificationError: 'InvalidModificationError',
145
NamespaceError: 'NamespaceError',
146
InvalidAccessError: 'InvalidAccessError', // deprecated
147
ValidationError: 'ValidationError', // deprecated
148
TypeMismatchError: 'TypeMismatchError', // deprecated
149
SecurityError: 'SecurityError',
150
NetworkError: 'NetworkError',
151
AbortError: 'AbortError',
152
URLMismatchError: 'URLMismatchError', // deprecated
153
QuotaExceededError: 'QuotaExceededError',
154
TimeoutError: 'TimeoutError',
155
InvalidNodeTypeError: 'InvalidNodeTypeError',
156
DataCloneError: 'DataCloneError',
157
EncodingError: 'EncodingError',
158
NotReadableError: 'NotReadableError',
159
UnknownError: 'UnknownError',
160
ConstraintError: 'ConstraintError',
161
DataError: 'DataError',
162
TransactionInactiveError: 'TransactionInactiveError',
163
ReadOnlyError: 'ReadOnlyError',
164
VersionError: 'VersionError',
165
OperationError: 'OperationError',
166
NotAllowedError: 'NotAllowedError',
167
OptOutError: 'OptOutError'
168
};
169
170
/**
171
* Legacy numeric exception codes
172
*/
173
const ExceptionCode = {
174
INDEX_SIZE_ERR: 1,
175
DOMSTRING_SIZE_ERR: 2,
176
HIERARCHY_REQUEST_ERR: 3,
177
WRONG_DOCUMENT_ERR: 4,
178
INVALID_CHARACTER_ERR: 5,
179
NO_DATA_ALLOWED_ERR: 6,
180
NO_MODIFICATION_ALLOWED_ERR: 7,
181
NOT_FOUND_ERR: 8,
182
NOT_SUPPORTED_ERR: 9,
183
INUSE_ATTRIBUTE_ERR: 10,
184
INVALID_STATE_ERR: 11,
185
SYNTAX_ERR: 12,
186
INVALID_MODIFICATION_ERR: 13,
187
NAMESPACE_ERR: 14,
188
INVALID_ACCESS_ERR: 15,
189
VALIDATION_ERR: 16,
190
TYPE_MISMATCH_ERR: 17,
191
SECURITY_ERR: 18,
192
NETWORK_ERR: 19,
193
ABORT_ERR: 20,
194
URL_MISMATCH_ERR: 21,
195
QUOTA_EXCEEDED_ERR: 22,
196
TIMEOUT_ERR: 23,
197
INVALID_NODE_TYPE_ERR: 24,
198
DATA_CLONE_ERR: 25
199
};
200
```
201
202
### Common Error Scenarios
203
204
**DOM Manipulation Errors:**
205
206
```javascript
207
const { DOMParser, DOMException } = require('@xmldom/xmldom');
208
209
const parser = new DOMParser();
210
const doc1 = parser.parseFromString('<root1></root1>', 'text/xml');
211
const doc2 = parser.parseFromString('<root2></root2>', 'text/xml');
212
213
try {
214
// WrongDocumentError: Cannot adopt node from different document
215
doc1.documentElement.appendChild(doc2.documentElement);
216
} catch (error) {
217
console.log(error.name); // 'WrongDocumentError'
218
}
219
220
try {
221
// HierarchyRequestError: Cannot insert node as child of itself
222
const root = doc1.documentElement;
223
root.appendChild(root);
224
} catch (error) {
225
console.log(error.name); // 'HierarchyRequestError'
226
}
227
228
try {
229
// NotFoundError: Attribute doesn't exist
230
const attr = doc1.documentElement.getAttributeNode('nonexistent');
231
doc1.documentElement.removeAttributeNode(attr);
232
} catch (error) {
233
console.log(error.name); // 'NotFoundError'
234
}
235
```
236
237
**Parsing Error Handling:**
238
239
```javascript
240
const { DOMParser, ParseError, onErrorStopParsing } = require('@xmldom/xmldom');
241
242
// Custom error handler
243
const parser = new DOMParser({
244
onError: (level, message, context) => {
245
const location = context ? `at line ${context.lineNumber}, column ${context.columnNumber}` : '';
246
console.log(`${level.toUpperCase()}: ${message} ${location}`);
247
248
if (level === 'fatalError') {
249
throw new ParseError(message, context);
250
}
251
}
252
});
253
254
// Using predefined error handlers
255
const strictParser = new DOMParser({
256
onError: onErrorStopParsing // Stops on any error
257
});
258
259
const veryStrictParser = new DOMParser({
260
onError: onWarningStopParsing // Stops on warnings too
261
});
262
```
263
264
**Error Recovery Strategies:**
265
266
```javascript
267
function parseXmlSafely(xmlString, fallbackValue = null) {
268
const parser = new DOMParser({
269
onError: (level, message) => {
270
console.warn(`XML ${level}: ${message}`);
271
// Log but continue parsing for warnings and errors
272
// Only fatal errors will throw
273
}
274
});
275
276
try {
277
return parser.parseFromString(xmlString, 'text/xml');
278
} catch (error) {
279
if (error instanceof ParseError) {
280
console.error('Failed to parse XML:', error.message);
281
return fallbackValue;
282
}
283
throw error; // Re-throw unexpected errors
284
}
285
}
286
287
// Usage
288
const doc = parseXmlSafely('<invalid><xml>', null);
289
if (doc === null) {
290
console.log('Parsing failed, using fallback');
291
}
292
```
293
294
**Validation and Error Prevention:**
295
296
```javascript
297
const { isValidMimeType, MIME_TYPE } = require('@xmldom/xmldom');
298
299
function safeParseFromString(xmlString, mimeType) {
300
// Validate MIME type before parsing
301
if (!isValidMimeType(mimeType)) {
302
throw new TypeError(`Invalid MIME type: ${mimeType}`);
303
}
304
305
// Validate input
306
if (typeof xmlString !== 'string') {
307
throw new TypeError('XML source must be a string');
308
}
309
310
if (xmlString.trim() === '') {
311
throw new Error('XML source cannot be empty');
312
}
313
314
const parser = new DOMParser();
315
return parser.parseFromString(xmlString, mimeType);
316
}
317
318
// Safe usage
319
try {
320
const doc = safeParseFromString('<root></root>', MIME_TYPE.XML_APPLICATION);
321
} catch (error) {
322
console.error('Safe parsing failed:', error.message);
323
}
324
```
325
326
### Error Logging and Debugging
327
328
```javascript
329
const { DOMParser } = require('@xmldom/xmldom');
330
331
// Comprehensive error logging
332
const debugParser = new DOMParser({
333
locator: true, // Enable location tracking
334
onError: (level, message, context) => {
335
const timestamp = new Date().toISOString();
336
const location = context && context.lineNumber ?
337
`${context.lineNumber}:${context.columnNumber}` : 'unknown';
338
339
const logEntry = {
340
timestamp,
341
level,
342
message,
343
location,
344
context: context ? { ...context } : null
345
};
346
347
console.log('XML Parse Event:', JSON.stringify(logEntry, null, 2));
348
349
// Store in application log
350
if (typeof applicationLogger !== 'undefined') {
351
applicationLogger.log(level, 'XML Parse Error', logEntry);
352
}
353
}
354
});
355
```