Skip to content

Commit

Permalink
Fix #3262: catch exceptions for POJONode when serializing, produce …
Browse files Browse the repository at this point in the history
…TextNode with failure
  • Loading branch information
cowtowncoder committed Feb 8, 2023
1 parent e02a92b commit c8f2a5e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,14 @@ protected void _serializeNonRecursive(JsonGenerator g, IteratorStack stack,
stack.push(currIt);
currIt = value.elements();
g.writeStartArray(value, value.size());
} else if (value instanceof POJONode) {
// [databind#3262] Problematic case, try to handle
try {
value.serialize(g, _context);
} catch (IOException | RuntimeException e) {
g.writeString(String.format("[ERROR: (%s) %s]",
e.getClass().getName(), e.getMessage()));
}
} else {
value.serialize(g, _context);
}
Expand Down
14 changes: 10 additions & 4 deletions src/test/java/com/fasterxml/jackson/failing/POJONode3262Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@

import com.fasterxml.jackson.databind.*;

// [databind#3262]: not sure what could be done here. The issue is that
// [databind#3262]: The issue is that
// `JsonNode.toString()` will use internal "default" ObjectMapper which
// does not (and cannot) have modules for external datatypes, such as
// Java 8 Date/Time types. One possibility would be catch IOException for
// POJONode, produce something like "ERROR: <ExceptionClass>" TextNode for that case?
// Java 8 Date/Time types. So we'll catch IOException/RuntimeException for
// POJONode, produce something like "[ERROR: (type) [msg]" TextNode for that case?
public class POJONode3262Test extends BaseMapTest
{
private final ObjectMapper MAPPER = newJsonMapper();
Expand All @@ -17,7 +17,13 @@ public void testAddJava8DateAsPojo() throws Exception
{
JsonNode node = MAPPER.createObjectNode().putPOJO("test", LocalDateTime.now());
String json = node.toString();

assertNotNull(json);

JsonNode result = MAPPER.readTree(json);
String msg = result.path("test").asText();
assertTrue("Wrong fail message: "+msg,
msg.startsWith("[ERROR:"));
assertTrue("Wrong fail message: "+msg,
msg.contains("InvalidDefinitionException"));
}
}

0 comments on commit c8f2a5e

Please sign in to comment.