0
# Error Handling
1
2
Structured error system with detailed error information for debugging and error recovery. JSON-LD operations can encounter various types of errors, and the library provides comprehensive error information to help with debugging and implementing robust error handling strategies.
3
4
## Capabilities
5
6
### JsonLdError Class
7
8
Custom error class that extends the standard JavaScript Error with additional JSON-LD specific information.
9
10
```javascript { .api }
11
/**
12
* Custom error class for JSON-LD operations
13
*/
14
class JsonLdError extends Error {
15
/**
16
* Creates a JSON-LD Error
17
* @param message - The error message
18
* @param name - The error type/name
19
* @param details - Additional error details
20
*/
21
constructor(message, name, details);
22
}
23
```
24
25
**Properties:**
26
- `name` (string): Error type identifier
27
- `message` (string): Human-readable error message
28
- `details` (object): Additional error-specific information
29
30
**Usage Examples:**
31
32
```javascript
33
const JsonLdError = require('jsonld/lib/JsonLdError');
34
35
// Create custom JSON-LD error
36
const error = new JsonLdError(
37
'Invalid context format',
38
'jsonld.InvalidLocalContext',
39
{
40
context: invalidContext,
41
code: 'invalid local context'
42
}
43
);
44
45
// Error properties
46
console.log(error.name); // 'jsonld.InvalidLocalContext'
47
console.log(error.message); // 'Invalid context format'
48
console.log(error.details); // { context: ..., code: '...' }
49
```
50
51
## Common Error Types
52
53
### Compaction Errors
54
55
Errors that occur during JSON-LD compaction operations.
56
57
**Error Names:**
58
- `jsonld.CompactError`: General compaction errors
59
- `jsonld.InvalidLocalContext`: Invalid context provided for compaction
60
61
**Common Scenarios:**
62
63
```javascript
64
try {
65
// This will throw because ctx cannot be null
66
await jsonld.compact(doc, null);
67
} catch (error) {
68
if (error.name === 'jsonld.CompactError') {
69
console.log('Compaction failed:', error.message);
70
console.log('Error code:', error.details.code); // 'invalid local context'
71
}
72
}
73
```
74
75
### Document Loading Errors
76
77
Errors related to loading remote documents and contexts.
78
79
**Error Names:**
80
- `jsonld.LoadDocumentError`: Failed to load remote document
81
- `jsonld.NullRemoteDocument`: Remote document is null or empty
82
- `jsonld.InvalidUrl`: Invalid URL provided
83
84
**Common Scenarios:**
85
86
```javascript
87
try {
88
const doc = await jsonld.expand('http://invalid-url.example');
89
} catch (error) {
90
if (error.name === 'jsonld.LoadDocumentError') {
91
console.log('Failed to load document:', error.details.url);
92
console.log('Cause:', error.details.cause);
93
if (error.details.remoteDoc) {
94
console.log('Remote doc info:', error.details.remoteDoc);
95
}
96
}
97
}
98
99
// Custom document loader error handling
100
jsonld.documentLoader = async (url) => {
101
try {
102
const response = await fetch(url);
103
if (!response.ok) {
104
throw new JsonLdError(
105
`HTTP ${response.status}: ${response.statusText}`,
106
'jsonld.LoadDocumentError',
107
{
108
code: 'loading document failed',
109
url: url,
110
status: response.status
111
}
112
);
113
}
114
return {
115
contextUrl: null,
116
document: await response.json(),
117
documentUrl: response.url
118
};
119
} catch (fetchError) {
120
throw new JsonLdError(
121
'Network error loading document',
122
'jsonld.LoadDocumentError',
123
{
124
code: 'loading document failed',
125
url: url,
126
cause: fetchError
127
}
128
);
129
}
130
};
131
```
132
133
### Syntax Errors
134
135
Errors related to invalid JSON-LD syntax or structure.
136
137
**Error Names:**
138
- `jsonld.SyntaxError`: Invalid JSON-LD syntax
139
- `jsonld.InvalidTypeValue`: Invalid @type value format
140
141
**Common Scenarios:**
142
143
```javascript
144
try {
145
// Invalid @type value (must be string or array of strings)
146
const doc = {
147
"@type": {invalid: "object"}
148
};
149
await jsonld.expand(doc);
150
} catch (error) {
151
if (error.name === 'jsonld.SyntaxError') {
152
console.log('Syntax error:', error.message);
153
console.log('Invalid value:', error.details.value);
154
console.log('Error code:', error.details.code); // 'invalid type value'
155
}
156
}
157
```
158
159
### RDF Processing Errors
160
161
Errors that occur during RDF operations.
162
163
**Error Names:**
164
- `jsonld.CanonizeError`: Canonicalization/normalization errors
165
- `jsonld.UnknownFormat`: Unknown input/output format
166
- `jsonld.UnknownDocumentLoader`: Unknown document loader type
167
168
**Common Scenarios:**
169
170
```javascript
171
try {
172
// Unknown input format
173
await jsonld.canonize(input, {inputFormat: 'application/turtle'});
174
} catch (error) {
175
if (error.name === 'jsonld.CanonizeError') {
176
console.log('Canonicalization failed:', error.message);
177
}
178
}
179
180
try {
181
// Unknown output format
182
await jsonld.toRDF(doc, {format: 'application/turtle'});
183
} catch (error) {
184
if (error.name === 'jsonld.UnknownFormat') {
185
console.log('Unknown format:', error.details.format);
186
}
187
}
188
```
189
190
### Context Processing Errors
191
192
Errors during context processing and resolution.
193
194
**Error Names:**
195
- `jsonld.InvalidLocalContext`: Invalid local context structure
196
- `jsonld.InvalidRemoteContext`: Invalid remote context
197
- `jsonld.RecursiveContextInclusion`: Circular context references
198
199
**Common Scenarios:**
200
201
```javascript
202
try {
203
await jsonld.processContext({}, circularContext);
204
} catch (error) {
205
if (error.name === 'jsonld.RecursiveContextInclusion') {
206
console.log('Circular context reference detected');
207
console.log('Context chain:', error.details.contextChain);
208
}
209
}
210
```
211
212
## Error Handling Patterns
213
214
### Basic Error Handling
215
216
```javascript
217
const handleJsonLdError = async (operation) => {
218
try {
219
return await operation();
220
} catch (error) {
221
if (error instanceof JsonLdError) {
222
console.error(`JSON-LD Error [${error.name}]:`, error.message);
223
if (error.details) {
224
console.error('Details:', error.details);
225
}
226
} else {
227
console.error('Unexpected error:', error);
228
}
229
throw error;
230
}
231
};
232
233
// Usage
234
const result = await handleJsonLdError(() =>
235
jsonld.compact(doc, context)
236
);
237
```
238
239
### Retry with Fallback
240
241
```javascript
242
const compactWithFallback = async (doc, context, fallbackContext) => {
243
try {
244
return await jsonld.compact(doc, context);
245
} catch (error) {
246
if (error.name === 'jsonld.LoadDocumentError') {
247
console.warn('Primary context failed, trying fallback:', error.message);
248
return await jsonld.compact(doc, fallbackContext);
249
}
250
throw error;
251
}
252
};
253
```
254
255
### Validation Before Processing
256
257
```javascript
258
const validateAndExpand = async (doc) => {
259
// Pre-validate document structure
260
if (!doc || typeof doc !== 'object') {
261
throw new JsonLdError(
262
'Document must be a non-null object',
263
'jsonld.InvalidInput',
264
{document: doc}
265
);
266
}
267
268
try {
269
return await jsonld.expand(doc, {safe: true});
270
} catch (error) {
271
if (error.name === 'jsonld.SyntaxError') {
272
// Handle syntax errors specifically
273
console.error('Document has invalid JSON-LD syntax');
274
console.error('Problem with:', error.details.value);
275
return null; // or return a default/cleaned version
276
}
277
throw error;
278
}
279
};
280
```
281
282
### Safe Mode Error Handling
283
284
```javascript
285
const safeJsonLdOperation = async (operation, ...args) => {
286
try {
287
// Always use safe mode for operations
288
const options = args[args.length - 1] || {};
289
args[args.length - 1] = {...options, safe: true};
290
291
return await operation(...args);
292
} catch (error) {
293
if (error.name?.startsWith('jsonld.')) {
294
// Log JSON-LD specific errors but don't crash
295
console.warn('JSON-LD operation failed safely:', error.message);
296
return null;
297
}
298
throw error; // Re-throw non-JSON-LD errors
299
}
300
};
301
302
// Usage
303
const compacted = await safeJsonLdOperation(jsonld.compact, doc, context);
304
if (compacted === null) {
305
// Handle the failure case
306
console.log('Compaction failed, using original document');
307
}
308
```
309
310
## Error Recovery Strategies
311
312
### Document Loading Recovery
313
314
```javascript
315
const loadDocumentWithRetry = async (url, maxRetries = 3) => {
316
for (let attempt = 1; attempt <= maxRetries; attempt++) {
317
try {
318
return await jsonld.get(url);
319
} catch (error) {
320
if (error.name === 'jsonld.LoadDocumentError' && attempt < maxRetries) {
321
console.warn(`Load attempt ${attempt} failed, retrying...`);
322
// Wait before retry (exponential backoff)
323
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
324
continue;
325
}
326
throw error;
327
}
328
}
329
};
330
```
331
332
### Context Fallback Chain
333
334
```javascript
335
const processContextWithFallbacks = async (activeCtx, contexts) => {
336
for (const context of contexts) {
337
try {
338
return await jsonld.processContext(activeCtx, context);
339
} catch (error) {
340
console.warn(`Context failed: ${context}`, error.message);
341
continue; // Try next context
342
}
343
}
344
345
throw new JsonLdError(
346
'All context options failed',
347
'jsonld.ContextProcessingError',
348
{contexts, lastError: error}
349
);
350
};
351
```
352
353
## Types
354
355
```javascript { .api }
356
/**
357
* JSON-LD error details structure
358
*/
359
interface JsonLdErrorDetails {
360
/**
361
* Error code identifier
362
*/
363
code?: string;
364
365
/**
366
* URL that caused the error (for loading errors)
367
*/
368
url?: string;
369
370
/**
371
* HTTP status code (for HTTP errors)
372
*/
373
status?: number;
374
375
/**
376
* The value that caused the error
377
*/
378
value?: any;
379
380
/**
381
* Context information
382
*/
383
context?: any;
384
385
/**
386
* Remote document information
387
*/
388
remoteDoc?: RemoteDocument;
389
390
/**
391
* Underlying cause of the error
392
*/
393
cause?: Error;
394
395
/**
396
* Additional context-specific details
397
*/
398
[key: string]: any;
399
}
400
401
/**
402
* Common JSON-LD error names
403
*/
404
type JsonLdErrorName =
405
| 'jsonld.CompactError'
406
| 'jsonld.LoadDocumentError'
407
| 'jsonld.NullRemoteDocument'
408
| 'jsonld.InvalidUrl'
409
| 'jsonld.SyntaxError'
410
| 'jsonld.InvalidTypeValue'
411
| 'jsonld.CanonizeError'
412
| 'jsonld.UnknownFormat'
413
| 'jsonld.UnknownDocumentLoader'
414
| 'jsonld.InvalidLocalContext'
415
| 'jsonld.InvalidRemoteContext'
416
| 'jsonld.RecursiveContextInclusion'
417
| 'jsonld.OptionsError';
418
419
/**
420
* Error handler function type
421
*/
422
type ErrorHandler = (error: JsonLdError) => void | Promise<void>;
423
```