Skip to content

Commit

Permalink
Improve handling of failure to deserialize java.util.regex.Pattern (F…
Browse files Browse the repository at this point in the history
  • Loading branch information
cowtowncoder authored Dec 15, 2023
1 parent 70a2c9d commit 15fa6ec
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.util.VersionUtil;
Expand Down Expand Up @@ -329,10 +330,20 @@ protected Object _deserialize(String value, DeserializationContext ctxt) throws
return ctxt.getTypeFactory().constructFromCanonical(value);
case STD_CURRENCY:
// will throw IAE if unknown:
return Currency.getInstance(value);
try {
return Currency.getInstance(value);
} catch (IllegalArgumentException e) {
// Looks like there is no more information
return ctxt.handleWeirdStringValue(_valueClass, value,
"Unrecognized currency");
}
case STD_PATTERN:
// will throw IAE (or its subclass) if malformed
return Pattern.compile(value);
try {
return Pattern.compile(value);
} catch (PatternSyntaxException e) {
return ctxt.handleWeirdStringValue(_valueClass, value,
"Invalid Pattern, problem: "+e.getDescription());
}
case STD_LOCALE:
return _deserializeLocale(value, ctxt);
case STD_CHARSET:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,15 @@ public void testClassWithParams() throws IOException
public void testCurrency() throws IOException
{
Currency usd = Currency.getInstance("USD");
assertEquals(usd, new ObjectMapper().readValue(q("USD"), Currency.class));
assertEquals(usd, MAPPER.readValue(q("USD"), Currency.class));

try {
MAPPER.readValue(q("poobah"), Currency.class);
fail("Should not pass!");
} catch (InvalidFormatException e) {
verifyException(e, "Cannot deserialize value of type `java.util.Currency` from String \"Poobah\"");
verifyException(e, "Unrecognized currency");
}
}

public void testFile() throws Exception
Expand Down Expand Up @@ -199,12 +207,13 @@ public void testPattern() throws IOException
assertEquals(exp.pattern(), result.pattern());

// [databind#3598]: should also handle invalid pattern serialization
// somehwat gracefully
// somewhat gracefully
try {
MAPPER.readValue(q("[abc"), Pattern.class);
fail("Should not pass");
} catch (InvalidFormatException e) {
verifyException(e, "not a valid textual representation, problem: Unclosed character class");
verifyException(e, "Cannot deserialize value of type `java.util.regex.Pattern` from String \"[abc\"");
verifyException(e, "Invalid pattern, problem");
}
}

Expand Down

0 comments on commit 15fa6ec

Please sign in to comment.