0
# Exception Handling
1
2
Jackson Core provides a comprehensive exception hierarchy for handling JSON processing errors with detailed location information and specific error types for different failure scenarios.
3
4
## Exception Hierarchy
5
6
### Base Exception Classes
7
8
```java { .api }
9
public abstract class JacksonException extends IOException {
10
protected JacksonException(String msg);
11
protected JacksonException(String msg, Throwable rootCause);
12
13
public abstract JsonLocation getLocation();
14
public abstract String getOriginalMessage();
15
public abstract Object getProcessor();
16
public String getMessageSuffix();
17
public String getMessage();
18
}
19
20
public abstract class JsonProcessingException extends JacksonException {
21
protected JsonProcessingException(String msg);
22
protected JsonProcessingException(String msg, JsonLocation loc);
23
protected JsonProcessingException(String msg, Throwable rootCause);
24
protected JsonProcessingException(String msg, JsonLocation loc, Throwable rootCause);
25
26
@Override
27
public JsonLocation getLocation();
28
public void clearLocation();
29
@Override
30
public String getOriginalMessage();
31
public String getMessageSuffix();
32
protected String _buildMessage();
33
}
34
```
35
36
### Parse Exceptions
37
38
```java { .api }
39
public class JsonParseException extends JsonProcessingException {
40
public JsonParseException(JsonParser p, String msg);
41
public JsonParseException(JsonParser p, String msg, Throwable rootCause);
42
public JsonParseException(JsonParser p, String msg, JsonLocation loc);
43
public JsonParseException(JsonParser p, String msg, JsonLocation loc, Throwable rootCause);
44
45
@Override
46
public JsonParser getProcessor();
47
public RequestPayload getRequestPayload();
48
public JsonParseException withRequestPayload(RequestPayload p);
49
}
50
```
51
52
### Generation Exceptions
53
54
```java { .api }
55
public class JsonGenerationException extends JsonProcessingException {
56
public JsonGenerationException(Throwable rootCause);
57
public JsonGenerationException(String msg);
58
public JsonGenerationException(String msg, Throwable rootCause);
59
public JsonGenerationException(Throwable rootCause, JsonGenerator g);
60
public JsonGenerationException(String msg, JsonGenerator g);
61
public JsonGenerationException(String msg, Throwable rootCause, JsonGenerator g);
62
63
@Override
64
public JsonGenerator getProcessor();
65
}
66
```
67
68
## Stream-Specific Exceptions
69
70
### Stream Read Exceptions
71
72
```java { .api }
73
public class StreamReadException extends JsonProcessingException {
74
public StreamReadException(JsonParser p, String msg);
75
public StreamReadException(JsonParser p, String msg, Throwable rootCause);
76
public StreamReadException(JsonParser p, String msg, JsonLocation loc);
77
public StreamReadException(JsonParser p, String msg, JsonLocation loc, Throwable rootCause);
78
79
@Override
80
public JsonParser getProcessor();
81
public RequestPayload getRequestPayload();
82
public StreamReadException withRequestPayload(RequestPayload p);
83
}
84
85
public class InputCoercionException extends StreamReadException {
86
protected final Class<?> _targetType;
87
88
public InputCoercionException(JsonParser p, String msg, JsonToken inputType, Class<?> targetType);
89
public InputCoercionException(JsonParser p, String msg, JsonLocation loc, JsonToken inputType, Class<?> targetType);
90
91
public Class<?> getTargetType();
92
public JsonToken getInputType();
93
}
94
95
public class StreamConstraintsException extends StreamReadException {
96
public StreamConstraintsException(String msg);
97
public StreamConstraintsException(String msg, JsonLocation loc);
98
}
99
```
100
101
### Stream Write Exceptions
102
103
```java { .api }
104
public class StreamWriteException extends JsonProcessingException {
105
public StreamWriteException(Throwable rootCause);
106
public StreamWriteException(String msg);
107
public StreamWriteException(String msg, Throwable rootCause);
108
public StreamWriteException(Throwable rootCause, JsonGenerator g);
109
public StreamWriteException(String msg, JsonGenerator g);
110
public StreamWriteException(String msg, Throwable rootCause, JsonGenerator g);
111
112
@Override
113
public JsonGenerator getProcessor();
114
}
115
```
116
117
## I/O Specific Exceptions
118
119
```java { .api }
120
public class JsonEOFException extends JsonParseException {
121
public JsonEOFException(JsonParser p, JsonToken token, String msg);
122
123
public JsonToken getTokenBeingDecoded();
124
}
125
```
126
127
## Location Information
128
129
```java { .api }
130
public class JsonLocation implements Serializable {
131
public static final JsonLocation NA;
132
133
public JsonLocation(ContentReference contentRef, long totalChars, int lineNr, int colNr);
134
public JsonLocation(ContentReference contentRef, long totalChars, long totalBytes, int lineNr, int colNr);
135
136
public ContentReference contentReference();
137
public Object getSourceRef();
138
public int getLineNr();
139
public int getColumnNr();
140
public long getCharOffset();
141
public long getByteOffset();
142
public String sourceDescription();
143
public String offsetDescription();
144
145
@Override
146
public String toString();
147
public String buildSourceDescription();
148
public int hashCode();
149
public boolean equals(Object other);
150
}
151
152
public class ContentReference implements Serializable {
153
public static ContentReference rawReference(Object rawContent);
154
public static ContentReference rawReference(boolean redactContent, Object rawContent);
155
public static ContentReference construct(boolean redactContent, Object rawContent);
156
public static ContentReference unknown();
157
158
public Object getRawContent();
159
public boolean hasTextualContent();
160
public String buildSourceDescription();
161
public boolean equals(Object other);
162
public int hashCode();
163
}
164
```
165
166
## Error Reporting
167
168
```java { .api }
169
public class RequestPayload implements Serializable {
170
protected byte[] _payloadAsBytes;
171
protected CharSequence _payloadAsText;
172
173
public RequestPayload(byte[] bytes);
174
public RequestPayload(CharSequence str);
175
176
public Object getRawPayload();
177
public String toString();
178
}
179
```
180
181
## Usage Examples
182
183
### Basic Exception Handling
184
185
```java
186
try {
187
JsonParser parser = factory.createParser(jsonInput);
188
while (parser.nextToken() != null) {
189
// Process tokens
190
}
191
parser.close();
192
} catch (JsonParseException e) {
193
System.err.println("Parse error at " + e.getLocation() + ": " + e.getOriginalMessage());
194
195
// Optional: Get request payload for debugging
196
RequestPayload payload = e.getRequestPayload();
197
if (payload != null) {
198
System.err.println("Input: " + payload.toString());
199
}
200
} catch (StreamReadException e) {
201
System.err.println("Stream read error: " + e.getMessage());
202
} catch (IOException e) {
203
System.err.println("I/O error: " + e.getMessage());
204
}
205
```
206
207
### Generation Exception Handling
208
209
```java
210
try {
211
JsonGenerator generator = factory.createGenerator(outputStream);
212
generator.writeStartObject();
213
generator.writeStringField("key", value);
214
generator.writeEndObject();
215
generator.close();
216
} catch (JsonGenerationException e) {
217
System.err.println("Generation error: " + e.getOriginalMessage());
218
JsonGenerator processor = (JsonGenerator) e.getProcessor();
219
if (processor != null) {
220
System.err.println("Generator context: " + processor.getOutputContext());
221
}
222
} catch (StreamWriteException e) {
223
System.err.println("Stream write error: " + e.getMessage());
224
} catch (IOException e) {
225
System.err.println("I/O error: " + e.getMessage());
226
}
227
```
228
229
### Constraint Violation Handling
230
231
```java
232
try {
233
JsonFactory factory = JsonFactory.builder()
234
.streamReadConstraints(StreamReadConstraints.builder()
235
.maxStringLength(1000)
236
.maxNestingDepth(10)
237
.build())
238
.build();
239
240
JsonParser parser = factory.createParser(jsonInput);
241
// ... parsing
242
} catch (StreamConstraintsException e) {
243
System.err.println("Constraint violation: " + e.getMessage());
244
System.err.println("Location: " + e.getLocation());
245
} catch (JsonParseException e) {
246
System.err.println("Parse error: " + e.getMessage());
247
}
248
```
249
250
### Input Coercion Error Handling
251
252
```java
253
try {
254
JsonParser parser = factory.createParser("{\"age\": \"not_a_number\"}");
255
parser.nextToken(); // START_OBJECT
256
parser.nextToken(); // FIELD_NAME
257
parser.nextToken(); // VALUE_STRING
258
259
int age = parser.getIntValue(); // This will throw InputCoercionException
260
} catch (InputCoercionException e) {
261
System.err.println("Cannot convert " + e.getInputType() +
262
" to " + e.getTargetType().getSimpleName());
263
System.err.println("Value: " + parser.getText());
264
} catch (IOException e) {
265
System.err.println("I/O error: " + e.getMessage());
266
}
267
```
268
269
### Detailed Error Information
270
271
```java
272
try {
273
// ... JSON processing
274
} catch (JsonProcessingException e) {
275
// Get location details
276
JsonLocation loc = e.getLocation();
277
if (loc != null) {
278
System.err.println("Error at line " + loc.getLineNr() +
279
", column " + loc.getColumnNr());
280
System.err.println("Character offset: " + loc.getCharOffset());
281
System.err.println("Source: " + loc.sourceDescription());
282
}
283
284
// Get original message without location decoration
285
String originalMsg = e.getOriginalMessage();
286
System.err.println("Original error: " + originalMsg);
287
288
// Get processor information
289
Object processor = e.getProcessor();
290
if (processor instanceof JsonParser) {
291
JsonParser p = (JsonParser) processor;
292
System.err.println("Parser state: " + p.getCurrentToken());
293
System.err.println("Current name: " + p.getCurrentName());
294
}
295
}
296
```
297
298
### Custom Error Handling with Payload
299
300
```java
301
public void parseJsonWithErrorReporting(String json) {
302
try {
303
JsonParser parser = factory.createParser(json);
304
// ... parsing logic
305
} catch (JsonParseException e) {
306
// Add request payload for better error reporting
307
RequestPayload payload = new RequestPayload(json);
308
JsonParseException enhancedException = e.withRequestPayload(payload);
309
310
logError("JSON parsing failed", enhancedException);
311
throw enhancedException;
312
}
313
}
314
315
private void logError(String message, JsonParseException e) {
316
logger.error("{}: {} at {}", message, e.getOriginalMessage(), e.getLocation());
317
318
RequestPayload payload = e.getRequestPayload();
319
if (payload != null) {
320
logger.debug("Input content: {}", payload.toString());
321
}
322
}
323
```
324
325
### EOF Exception Handling
326
327
```java
328
try {
329
JsonParser parser = factory.createParser(incompleteJson);
330
while (parser.nextToken() != null) {
331
// Process tokens
332
}
333
} catch (JsonEOFException e) {
334
JsonToken expectedToken = e.getTokenBeingDecoded();
335
System.err.println("Unexpected end of input, expected: " + expectedToken);
336
System.err.println("At location: " + e.getLocation());
337
}
338
```
339
340
### Recovery Strategies
341
342
```java
343
public List<JsonNode> parseJsonArray(String jsonArray, boolean lenient) {
344
List<JsonNode> results = new ArrayList<>();
345
346
try {
347
JsonParser parser = factory.createParser(jsonArray);
348
parser.nextToken(); // START_ARRAY
349
350
while (parser.nextToken() != JsonToken.END_ARRAY) {
351
try {
352
JsonNode node = parser.readValueAsTree();
353
results.add(node);
354
} catch (JsonParseException e) {
355
if (lenient) {
356
logger.warn("Skipping invalid JSON element: " + e.getMessage());
357
parser.skipChildren(); // Skip malformed element
358
} else {
359
throw e;
360
}
361
}
362
}
363
} catch (IOException e) {
364
if (!lenient) {
365
throw new RuntimeException("JSON parsing failed", e);
366
}
367
logger.error("Failed to parse JSON array", e);
368
}
369
370
return results;
371
}
372
```