Skip to main content

JsonProcessingException Is Gone in Jackson 3: JacksonException, Unchecked Errors and Migrating Your try/catch

Jackson 3 replaces the checked JsonProcessingException with the unchecked tools.jackson.core.JacksonException. See the new exception family, the catch blocks that compile but no longer catch anything, a Spring Boot 4.2 handler that turns server bugs into 400s, a @Transactional rollback change, and what OpenRewrite and sed each miss, all with captured output.

You upgrade to Jackson 3 (or to Spring Boot 4, which brings it with it), and the compiler says it cannot find JsonProcessingException. The obvious fix is to find the new name, replace it everywhere and move on. The name is easy: it is tools.jackson.core.JacksonException. The part that costs time is that the new class is unchecked, so the compiler stops telling you where Jackson errors can happen, and some of your old catch blocks keep compiling while catching nothing.

This article starts with the one-line answer, then walks through the new exception family, what each failure throws, which old handlers silently die, what changes in a Spring Boot 4 web app and in @Transactional methods, and what OpenRewrite and a plain text substitution each get right and wrong on a small project. Every output block comes from the exceptions module of the companion repository.

Versions used. Jackson 3.3.0 (tools.jackson) side by side with Jackson 2.23.0, JDK Temurin 25.0.5.1, Spring Boot 4.2.0 (GA 19 November 2026), which manages Jackson 3.1.8, plus 3.1.8 and 3.2.4 for one comparison. Migration run with rewrite-maven-plugin 6.46.1 and rewrite-jackson 1.29.0. Code: asmhatre/jackson3-by-example, module exceptions.

JsonProcessingException is now JacksonException, and it is unchecked

In Java, a checked exception (anything under Exception that is not a RuntimeException) must be caught or declared with throws, and the compiler enforces it. An unchecked one can travel up the stack without any code mentioning it. Jackson 2 errors were checked, because they extended IOException. Jackson 3 moved the whole family under RuntimeException.

The picture below shows the move. Read the two columns from the top: the only difference in the third row is what sits above it, and that one difference drives everything else on this page.

Jackson 2 (checked)Jackson 3 (unchecked)ExceptionExceptionIOExceptionRuntimeExceptionJacksonExceptionJacksonExceptionJsonProcessingExceptionthe five branches belowThe class you used to catch has no Jackson 3 namesake. Its job moved up one level,and the whole family left the IOException branch.
Jackson 2Jackson 3
com.fasterxml.jackson.core.JsonProcessingExceptiontools.jackson.core.JacksonException
com.fasterxml.jackson.databind.JsonMappingExceptiontools.jackson.databind.DatabindException
com.fasterxml.jackson.core.JsonParseExceptiontools.jackson.core.exc.StreamReadException
com.fasterxml.jackson.core.JsonGenerationExceptiontools.jackson.core.exc.StreamWriteException
com.fasterxml.jackson.core.io.JsonEOFExceptiontools.jackson.core.exc.UnexpectedEndOfInputException
a raw IOException from a file or streamtools.jackson.core.exc.JacksonIOException
JsonMappingException.Reference.getFieldName()JacksonException.Reference.getPropertyName()

The first five rows are the renames listed in the project’s Jackson 3 migration notes; the last two were observed here. If you simply swap the package in the import and keep the old class name, this is what javac says:

From 09-compile-errors.txt:

=== OldImport.java ===
OldImport.java:2: error: cannot find symbol
import tools.jackson.core.JsonProcessingException;
                         ^
  symbol:   class JsonProcessingException
  location: package tools.jackson.core
OldImport.java:6: error: cannot find symbol
    Order read(JsonMapper mapper, String json) throws JsonProcessingException {
                                                      ^
  symbol:   class JsonProcessingException
  location: class OldImport
2 errors

With the new name, no throws clause is needed and a lambda may call the mapper directly, as in E07Handling.java:

List<String> docs = List.of("{\"id\":1,\"quantity\":1}", "{\"id\":", "{\"id\":3,\"quantity\":1}");
try {
    docs.stream().map(d -> MAPPER.readValue(d, Order.class)).forEach(o -> System.out.println("parsed " + o.id()));
} catch (JacksonException e) {
    System.out.println("pipeline aborted: " + e.getClass().getSimpleName());
Why did Jackson make this change?

The proposal is JSTEP-4. Its argument is that checked exceptions became a burden once streams and functional style arrived in Java 8, and that changing the base class was only possible in a new major version. Both package name and exception base changed together, which is why a 2.x and a 3.x mapper can live in one JVM, as this module does.

Going deeper

The Jackson 3 exception family has five branches

JacksonException is the root. Directly under it are five classes, and knowing which one you are looking at usually tells you whose problem it is. The diagram is the mental model to keep; the colours are a first guess about blame, which the later section on catching refines.

JacksonExceptionStreamReadExceptionStreamConstraintsExceptionDatabindExceptionStreamWriteExceptionJacksonIOExceptiontext is notvalid JSONinput exceedsa safety limitJSON does notfit your typesgenerator usedwronglythe stream orfile failedusually the sender: rejectsender, ORyour classesyour codetransport: retry?StreamConstraintsException is a sibling of StreamReadException, not a child,and InvalidDefinitionException (your bug) lives inside DatabindException.

The full tree was not typed from documentation. A program scans the two jars with reflection; this is its Jackson 3 half, from 01-hierarchy.txt:

== Jackson 3.3.0 ==
tools.jackson.core.JacksonException  (extends java.lang.RuntimeException)
  JacksonIOException  [tools.jackson.core.exc]
  StreamConstraintsException  [tools.jackson.core.exc]
  StreamReadException  [tools.jackson.core.exc]
    InputCoercionException  [tools.jackson.core.exc]
    UnexpectedEndOfInputException  [tools.jackson.core.exc]
  StreamWriteException  [tools.jackson.core.exc]
  DatabindException  [tools.jackson.databind]
    UnresolvedForwardReference  [tools.jackson.databind.deser]
    DeferredBindingException  [tools.jackson.databind.exc]
    InvalidDefinitionException  [tools.jackson.databind.exc]
    JsonNodeException  [tools.jackson.databind.exc]
    MismatchedInputException  [tools.jackson.databind.exc]
      InvalidFormatException  [tools.jackson.databind.exc]
      InvalidNullException  [tools.jackson.databind.exc]
      InvalidTypeIdException  [tools.jackson.databind.exc]
      PropertyBindingException  [tools.jackson.databind.exc]
        IgnoredPropertyException  [tools.jackson.databind.exc]
        UnrecognizedPropertyException  [tools.jackson.databind.exc]
      DateTimeParseException  [tools.jackson.databind.ext.javatime]
    MissingInjectableValueExcepion  [tools.jackson.databind.exc]  @Deprecated
      MissingInjectableValueException  [tools.jackson.databind.exc]
    ValueInstantiationException  [tools.jackson.databind.exc]

Two things in that tree surprise people. First, JsonMappingException is gone, and DatabindException (which in 2.x was only its parent) takes its place. Second, there is no MismatchedInputException at the top level: it is where most “your JSON has the wrong shape” errors end up, one level under DatabindException, with InvalidFormatException and UnrecognizedPropertyException under it.

The Jackson 2 tree, for comparison

Same program, same run, from 01-hierarchy.txt:

== Jackson 2.23.0 ==
com.fasterxml.jackson.core.JacksonException  (extends java.io.IOException)
  JsonProcessingException  [com.fasterxml.jackson.core]
    StreamConstraintsException  [com.fasterxml.jackson.core.exc]
    StreamReadException  [com.fasterxml.jackson.core.exc]
      JsonParseException  [com.fasterxml.jackson.core]
        JsonEOFException  [com.fasterxml.jackson.core.io]
      InputCoercionException  [com.fasterxml.jackson.core.exc]
    StreamWriteException  [com.fasterxml.jackson.core.exc]
      JsonGenerationException  [com.fasterxml.jackson.core]
    DatabindException  [com.fasterxml.jackson.databind]
      JsonMappingException  [com.fasterxml.jackson.databind]
        UnresolvedForwardReference  [com.fasterxml.jackson.databind.deser]
        InvalidDefinitionException  [com.fasterxml.jackson.databind.exc]
        MismatchedInputException  [com.fasterxml.jackson.databind.exc]
          InvalidFormatException  [com.fasterxml.jackson.databind.exc]
          InvalidNullException  [com.fasterxml.jackson.databind.exc]
          InvalidTypeIdException  [com.fasterxml.jackson.databind.exc]
          PropertyBindingException  [com.fasterxml.jackson.databind.exc]
            IgnoredPropertyException  [com.fasterxml.jackson.databind.exc]
            UnrecognizedPropertyException  [com.fasterxml.jackson.databind.exc]
        MissingInjectableValueExcepion  [com.fasterxml.jackson.databind.exc]
        ValueInstantiationException  [com.fasterxml.jackson.databind.exc]

Jackson 3 JacksonException superclass chain: JacksonException -> RuntimeException -> Exception -> Throwable
Jackson 2 JacksonException superclass chain: JacksonException -> IOException -> Exception -> Throwable

Note that 2.x already had a JacksonException (a checked one, extending IOException) and a DatabindException. Code written against the 2.x JacksonException therefore migrates by package rename alone, while still changing from checked to unchecked.

Going deeper
  • E01Hierarchy.java prints the tree from whatever jars are on your classpath.
  • MissingInjectableValueExcepion (misspelled) is still present and marked deprecated, with a correctly spelled subclass.
  • Polymorphic deserialization covers the type-id failures behind InvalidTypeIdException.

What throws what: one input per failure

Names are easier to remember next to the input that produces them. Each line below is a real call against a default JsonMapper (except where “strict on” says otherwise).

A few of the triggers, from E02Triggers.java:

show("syntax error", () -> MAPPER.readValue("{\"id\": 1, \"quantity\": }", Order.class));
show("truncated input", () -> MAPPER.readValue("{\"id\": 1, \"lines\": [", Order.class));
show("number too big for int", () -> MAPPER.readValue("{\"id\":1,\"quantity\":99999999999}", Order.class));

Reading failures, from 02-triggers.txt:

== reading: the text is not valid JSON ==
-- syntax error
   tools.jackson.core.exc.StreamReadException
   Unexpected character ('}' (code 125)): expected a value
-- truncated input
   tools.jackson.core.exc.UnexpectedEndOfInputException
   Unexpected end-of-input: expected close marker for Array (start marker at [Source: REDACTED (`StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION` disabled); ...
-- number too big for int
   tools.jackson.core.exc.InputCoercionException
   Numeric value (99999999999) out of range of `int` (-2147483648 - 2147483647)
-- nesting 1000 deep
   tools.jackson.core.exc.StreamConstraintsException
   Document nesting depth (501) exceeds the maximum allowed (500, from `StreamReadConstraints.getMaxNestingDepth()`)
-- duplicate key (strict on)
   tools.jackson.core.exc.StreamReadException
   Duplicate Object property "id"

Valid JSON that does not fit, from 02-triggers.txt:

== reading: valid JSON, wrong shape ==
-- string where int expected
   tools.jackson.databind.exc.InvalidFormatException
   Cannot deserialize value of type `long` from String "abc": not a valid `long` value
-- object where array expected
   tools.jackson.databind.exc.MismatchedInputException
   Cannot deserialize value of type `java.util.ArrayList<com.ankurm.exceptions.Order$Line>` from Object value (token `JsonToken.START_OBJECT`)
-- null for a primitive
   tools.jackson.databind.exc.MismatchedInputException
   Cannot map `null` into type `long` (set `DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES` to 'false' to allow)
-- primitive left out of a record
   no exception, result = Order[id=1, quantity=0, lines=null]
-- unknown property (strict on)
   tools.jackson.databind.exc.UnrecognizedPropertyException
   Unrecognized property "colour" (class com.ankurm.exceptions.Order), not marked as ignorable
-- trailing token
   tools.jackson.databind.exc.MismatchedInputException
   Trailing token (`JsonToken.START_OBJECT`) found after value (bound as `com.ankurm.exceptions.Order`): not allowed as per `DeserializationFeature.FAIL_ ...
-- empty input
   tools.jackson.databind.exc.MismatchedInputException
   No content to map due to end-of-input
-- unknown type id
   tools.jackson.databind.exc.InvalidTypeIdException
   Could not resolve type id 'square' as a subtype of `com.ankurm.exceptions.E02Triggers$Figure`: known type ids = [circle]
-- interface with no type info
   tools.jackson.databind.exc.InvalidDefinitionException
   Cannot construct instance of `com.ankurm.exceptions.E02Triggers$Shape` (no Creators, like default constructor, exist): abstract types either need to b ...
-- record constructor rejects
   tools.jackson.databind.exc.ValueInstantiationException
   cause: java.lang.IllegalArgumentException
   Cannot construct instance of `com.ankurm.exceptions.E02Triggers$Positive`, problem: n must be positive, got -1
-- tree: asInt() on text
   tools.jackson.databind.exc.JsonNodeException
   'StringNode' method `asInt()` cannot coerce value "abc" to `int`: value not a valid String representation of `int`

Writing, real I/O, and two calls that do not parse text, from 02-triggers.txt:

== writing ==
-- getter throws
   tools.jackson.databind.DatabindException
   cause: java.lang.IllegalStateException
   lazy collection not initialised
-- generator misuse
   tools.jackson.core.exc.StreamWriteException
   Cannot write a string, expecting a property name (context: Object)
== real I/O ==
-- file does not exist
   tools.jackson.core.exc.JacksonIOException
   cause: java.nio.file.NoSuchFileException
   no-such-file.json
-- stream breaks mid-read
   tools.jackson.core.exc.JacksonIOException
   cause: java.io.IOException
   Connection reset
== calls that do not parse text ==
-- null String
   java.lang.IllegalArgumentException
   argument "content" is null
-- convertValue with bad data
   tools.jackson.databind.exc.InvalidFormatException
   Cannot deserialize value of type `long` from String "abc": not a valid `long` value

Look at the last two entries. Passing a null String is a programming error and gives a plain IllegalArgumentException. convertValue with bad data now throws the Jackson exception itself. In Jackson 2 it wrapped that in IllegalArgumentException, so a handler written for the old wrapper no longer matches. The same inputs against both major versions show that change and a few others:

Jackson 2.23.0 against Jackson 3.3.0, from 04-behaviour-diff.txt:

-- convertValue(map with bad value)
   J2: java.lang.IllegalArgumentException  (cause: InvalidFormatException)
   J3: tools.jackson.databind.exc.InvalidFormatException
-- readValue(file that does not exist)
   J2: java.io.FileNotFoundException
   J3: tools.jackson.core.exc.JacksonIOException  (cause: FileNotFoundException)
-- readValue(stream that throws IOException)
   J2: java.io.IOException
   J3: tools.jackson.core.exc.JacksonIOException  (cause: IOException)
-- writeValueAsString(getter that throws)
   J2: com.fasterxml.jackson.databind.JsonMappingException  (cause: IllegalStateException)
   J3: tools.jackson.databind.DatabindException  (cause: IllegalStateException)
-- readValue("{\"id\":null}") into a long
   J2: no exception -> Order[id=0, quantity=1, lines=null]
   J3: tools.jackson.databind.exc.MismatchedInputException
-- readValue(valid object followed by junk)
   J2: no exception -> Order[id=1, quantity=2, lines=null]
   J3: tools.jackson.core.exc.StreamReadException
-- readValue(unknown property)
   J2: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException
   J3: no exception -> Order[id=1, quantity=2, lines=null]

Three of these are not about the exception hierarchy at all but about defaults that flipped: null into a primitive and trailing junk now fail, and unknown properties no longer do. Your error handling can start or stop firing for that reason alone. The full list of flipped defaults is in the ObjectMapper and JsonMapper guide.

A missing primitive depends on your 3.x line. Spring Boot 4.2.0 gives you Jackson 3.1.8. There, leaving a primitive record component out of the JSON throws. On 3.2.4 and 3.3.0 the same input binds 0. An explicit null throws on all three. If you rely on the exception for validation, a Jackson upgrade removes it without any compile error. Use a boxed type plus Bean Validation, or enable a strictness feature deliberately and test it.

The same program on three versions, from 10-missing-primitive-by-version.txt:

jackson-databind 3.1.8
  {"sku":"A","count":null}  ->  MismatchedInputException: Cannot map `null` into type `int` (set `DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES` to 'false' to allow)
  {"sku":"A"}  ->  MismatchedInputException: Cannot map `null` into type `int` (set `DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES` to 'false' to allow)
jackson-databind 3.2.4
  {"sku":"A","count":null}  ->  MismatchedInputException: Cannot map `null` into type `int` (set `DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES` to 'false' to allow)
  {"sku":"A"}  ->  Stock[sku=A, count=0]
jackson-databind 3.3.0
  {"sku":"A","count":null}  ->  MismatchedInputException: Cannot map `null` into type `int` (set `DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES` to 'false' to allow)
  {"sku":"A"}  ->  Stock[sku=A, count=0]
Going deeper

The dangerous change: catch (IOException) that compiles and catches nothing

If a try block contains only Jackson calls, an old catch (IOException e) becomes a compile error, which is good: you are told. If the block also does real I/O, such as reading a file, IOException is still possible, the code still compiles, and the Jackson half of the handler is simply gone.

try { Files.readString(file) mapper.readValue(…)}throws IOExceptionthrows JacksonExceptioncatch (IOException e)still runs, still compilesnothing matchesexception leaves the methodThe file read keeps the catch clause legal, so javac has nothing to complain about.Only the half that handled bad JSON is dead.

Here is the trap and its fix, from E03SilentCatch.java:

static String loadJ3(Path file) {
    try {
        Order order = J3.readValue(Files.readString(file), Order.class);
        return "loaded order " + order.id();
    } catch (IOException e) {                  // still compiles: file errors only
        return "fallback: " + e.getClass().getSimpleName();
    }
}

static String loadJ3Fixed(Path file) {
    try {
        Order order = J3.readValue(Files.readString(file), Order.class);
        return "loaded order " + order.id();
    } catch (IOException | tools.jackson.core.JacksonException e) {
        return "fallback: " + e.getClass().getSimpleName();
    }
}

Run against a missing file and a file with broken JSON, from 03-silent-catch.txt:

== missing file ==
Jackson 2, catch (IOException)
   fallback: NoSuchFileException
Jackson 3, catch (IOException)
   fallback: NoSuchFileException
Jackson 3, catch (IOException | JacksonException)
   fallback: NoSuchFileException
== file with malformed JSON ==
Jackson 2, catch (IOException)
   fallback: JsonParseException
Jackson 3, catch (IOException)
   ESCAPED: tools.jackson.core.exc.StreamReadException
Jackson 3, catch (IOException | JacksonException)
   fallback: StreamReadException

The missing-file case behaves identically in all three variants, which is exactly why a test that only covers “file not found” passes after the upgrade.

The compiler is helpful in the other cases, and these are the messages you will meet:

Only Jackson inside the try, from 09-compile-errors.txt:

=== CatchIOException.java ===
CatchIOException.java:9: error: exception IOException is never thrown in body of corresponding try statement
        } catch (IOException e) {
          ^
1 error

A subtype beside or after its parent, from 09-compile-errors.txt:

=== RelatedMultiCatch.java ===
RelatedMultiCatch.java:10: error: Alternatives in a multi-catch statement cannot be related by subclassing
        } catch (JacksonException | DatabindException e) {
                                    ^
  Alternative DatabindException is a subclass of alternative JacksonException
1 error

=== WrongOrder.java ===
WrongOrder.java:12: error: exception DatabindException has already been caught
        } catch (DatabindException e) {
          ^
1 error
Search for these four shapes after any upgrade. catch (IOException near a mapper call; throws IOException on a method that wraps a mapper call (its callers believe the declaration); catch (IllegalArgumentException around convertValue; and broad catch (RuntimeException blocks that now receive parse errors they never saw before.
Going deeper
  • review-catches.sh greps for the first three and the broad catches.
  • broken holds every file that must not compile.

Catch where you can act, and classify before you answer

Unchecked does not mean “ignore”. It means you now choose the place. The useful rule: let it propagate unless this method can do something specific, such as skip one bad record, return a fallback, or translate the failure into your own domain exception. When you do catch, ask whose fault it is, because the same root class covers a malformed request, a dropped connection and a bug in your own classes.

A small classifier, where the order of the checks matters, from E07Handling.java:

/** Order of the branches matters: InvalidDefinitionException IS a DatabindException. */
static Fault classify(JacksonException e) {
    if (e instanceof JacksonIOException) return Fault.TRANSPORT;
    if (e instanceof InvalidDefinitionException) return Fault.OUR_BUG;
    if (e instanceof StreamReadException || e instanceof StreamConstraintsException) return Fault.BAD_INPUT;
    if (e instanceof DatabindException) return Fault.BAD_INPUT;
    return Fault.OUR_BUG;
}

Its answers, followed by a tempting catch clause that misses a case, from 07-handling.txt:

== who is at fault ==
syntax error               UnexpectedEndOfInputException BAD_INPUT
wrong type                 InvalidFormatException       BAD_INPUT
too deep                   StreamConstraintsException   BAD_INPUT
no way to construct type   InvalidDefinitionException   OUR_BUG
connection reset           JacksonIOException           TRANSPORT

== a catch that misses StreamConstraintsException ==
slipped past catch (StreamReadException | DatabindException): StreamConstraintsException

InvalidDefinitionException means Jackson cannot work out how to build your type, for example an interface with no type information. It is a DatabindException, so a handler that treats all databind errors as bad input will blame the client for your mistake. In the other direction, StreamConstraintsException (input too deep or too large) sits beside StreamReadException, so catch (StreamReadException | DatabindException e) lets it through. Treat the classifier as a starting point: a DatabindException from a getter that throws during writing is also your fault, and only the call site knows which direction it was going.

Streams and futures

You can now call readValue inside a lambda. The cost is that one bad element aborts the pipeline, so decide per element if you need to. Asynchronous code has its own wrinkle: join() hands you a CompletionException, and your catch (JacksonException e) does not match it.

From 07-handling.txt:

== streams: no try/catch needed, one bad element ends the pipeline ==
parsed 1
pipeline aborted: UnexpectedEndOfInputException
skip-and-report instead:
  parsed 1
  skipped {"id": (UnexpectedEndOfInputException)
  parsed 3

== CompletableFuture wraps it ==
join() threw CompletionException, cause UnexpectedEndOfInputException
exceptionally(): sees CompletionException wrapping UnexpectedEndOfInputException

== an old catch (RuntimeException) now swallows Jackson errors ==
generic handler got UnexpectedEndOfInputException
Going deeper
  • E07Handling.java contains every case in that output.
  • With ExecutorService.submit the same wrapping idea applies through ExecutionException; that variant was not run here.

Reading the exception: path, position and the value you should not log

A Jackson exception is more than a message. It carries where the problem was in the document (getLocation()), which field it was binding (getPath()), and for some subtypes the rejected value and the target type. This input hides something that looks like a card number in the wrong field:

From E05Location.java:

static final String BAD = """
        {"id": 7,
         "quantity": 2,
         "lines": [ {"sku": "A-1", "qty": 1},
                    {"sku": "B-2", "qty": "card=4111111111111111"} ]}""";

What the exception knows, from 05-location-and-path.txt:

class              : InvalidFormatException
getOriginalMessage : Cannot deserialize value of type `int` from String "card=4111111111111111": not a valid `int` value
getLocation        : line 4, column 35, char offset 98
getPathReference   : com.ankurm.exceptions.Order["lines"]->java.util.ArrayList[1]->com.ankurm.exceptions.Order$Line["qty"]
field path         : lines[1].qty
getValue           : card=4111111111111111
getTargetType      : int

getMessage():
Cannot deserialize value of type `int` from String "card=4111111111111111": not a valid `int` value
 at [Source: REDACTED (`StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION` disabled); byte offset: #UNKNOWN] (through reference chain: com.ankurm.exceptions.Order["lines"]->java.util.ArrayList[1]->com.ankurm.exceptions.Order$Line["qty"])

The source text is redacted in the message (REDACTED), but the offending value is not: it is in getOriginalMessage(), in getMessage() and in getValue(). Returning either message to a client, or logging it for data you treat as sensitive, leaks it. The field path, built from names and indexes only, is safe to return:

From E05Location.java:

/** "lines[1].qty": safe to show a client, because it contains names and indexes but no values. */
static String fieldPath(JacksonException e) {
    return e.getPath().stream()
            .map(r -> r.getPropertyName() != null ? "." + r.getPropertyName() : "[" + r.getIndex() + "]")
            .collect(Collectors.joining())
            .replaceFirst("^\\.", "");
String input: the message no longer shows line and column. On the same one-line document, Jackson 2.23.0 prints line: 1, column: 23 inside the message. Jackson 3.3.0 prints byte offset: #UNKNOWN for String input, although getLineNr() and getColumnNr() are still correct. If your log search relied on the line number in the text, log the two getters explicitly.

From 05-location-and-path.txt:

== where the position shows up: same broken text, three ways ==
Jackson 2, String input : line: 1, column: 23
Jackson 3, String input : byte offset: #UNKNOWN   but getLineNr()=1, getColumnNr()=23
Jackson 3, byte[] input : byte offset: #22   getLineNr()=1, getColumnNr()=23

Real stack traces

In a log, the first line names the class, the “through reference chain” part names the field, and the first frame from your own package names the call. A syntax error comes straight from the parser:

From 06-stack-traces.txt:

===== malformed JSON =====
tools.jackson.core.exc.StreamReadException: Unexpected character ('}' (code 125)): expected a value
 at [Source: REDACTED (`StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION` disabled); byte offset: #UNKNOWN]
	at tools.jackson.core.JsonParser._constructReadException(JsonParser.java:1914)
	at tools.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:1071)
	at tools.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:774)
	at tools.jackson.databind.deser.bean.BeanDeserializer._deserializeUsingPropertyBased(BeanDeserializer.java:807)
	at tools.jackson.databind.deser.bean.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1724)
	at tools.jackson.databind.deser.bean.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:690)
	at tools.jackson.databind.deser.bean.BeanDeserializer.deserialize(BeanDeserializer.java:209)
	at tools.jackson.databind.deser.DeserializationContextExt.readRootValue(DeserializationContextExt.java:352)
	at tools.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2696)
	at tools.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:1556)
	at com.ankurm.exceptions.E06StackTraces.lambda$main$0(E06StackTraces.java:16)
	at com.ankurm.exceptions.E06StackTraces.trace(E06StackTraces.java:25)
	at com.ankurm.exceptions.E06StackTraces.main(E06StackTraces.java:16)

When your own record constructor rejects a value, Jackson wraps it, and the useful line is under Caused by:

Top of the trace, from 06-stack-traces.txt:

===== record constructor rejects the value =====
tools.jackson.databind.exc.ValueInstantiationException: Cannot construct instance of `com.ankurm.exceptions.E06StackTraces$Positive`, problem: n must be positive, got -1
 at [Source: REDACTED (`StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION` disabled); byte offset: #UNKNOWN]
	at tools.jackson.databind.exc.ValueInstantiationException.from(ValueInstantiationException.java:44)
	at tools.jackson.databind.DeserializationContext.instantiationException(DeserializationContext.java:2282)

and its cause, further down the same file, 06-stack-traces.txt:

Caused by: java.lang.IllegalArgumentException: n must be positive, got -1
	at com.ankurm.exceptions.E06StackTraces$Positive.<init>(E06StackTraces.java:11)
	at java.base/java.lang.invoke.MethodHandle.invokeWithArguments(MethodHandle.java:735)
	at tools.jackson.databind.introspect.AnnotatedConstructor.call(AnnotatedConstructor.java:134)
	at tools.jackson.databind.deser.std.StdValueInstantiator.createFromObjectWith(StdValueInstantiator.java:287)
The long one: a wrong type inside a list

The first lines of about thirty, nearly all Jackson internals, from 06-stack-traces.txt:

===== wrong type inside a list =====
tools.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `int` from String "two": not a valid `int` value
 at [Source: REDACTED (`StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION` disabled); byte offset: #UNKNOWN] (through reference chain: com.ankurm.exceptions.Order["lines"]->java.util.ArrayList[0]->com.ankurm.exceptions.Order$Line["qty"])
	at tools.jackson.databind.exc.InvalidFormatException.from(InvalidFormatException.java:40)
	at tools.jackson.databind.DeserializationContext.weirdStringException(DeserializationContext.java:2228)
	at tools.jackson.databind.DeserializationContext.handleWeirdStringValue(DeserializationContext.java:1519)
	at tools.jackson.databind.deser.std.StdDeserializer._parseIntPrimitive(StdDeserializer.java:832)
	at tools.jackson.databind.deser.std.StdDeserializer._parseIntPrimitive(StdDeserializer.java:812)
	at tools.jackson.databind.deser.jdk.NumberDeserializers$IntegerDeserializer.deserialize(NumberDeserializers.java:617)
What if you switch source inclusion on?

With StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION the document itself becomes part of the location, card number and all, from 05-location-and-path.txt:

== the same input with StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION enabled ==
(String)"{"id": 7,
 "quantity": 2,
 "lines": [ {"sku": "A-1", "qty": 1},
            {"sku": "B-2", "qty": "card=4111111111111111"} ]}"

Keep it off outside local debugging.

Going deeper

Custom deserializers, your own throws, and collecting several errors

If you write a ValueDeserializer and let a NumberFormatException escape, Jackson wraps it in a plain DatabindException with the path attached. Reporting the problem through the DeserializationContext gives a more specific type that callers can distinguish.

Both styles, from E08CustomAndCollect.java:

/** Throws a plain runtime exception: the author "forgot" Jackson. */
public static class Plain extends ValueDeserializer<Integer> {
    @Override public Integer deserialize(JsonParser p, DeserializationContext ctxt) {
        return Integer.parseInt(p.getString());
    }
}

/** Reports the same failure through the context, which yields a Jackson exception with a path. */
public static class Reported extends ValueDeserializer<Integer> {
    @Override public Integer deserialize(JsonParser p, DeserializationContext ctxt) {
        String s = p.getString();
        try {
            return Integer.parseInt(s);
        } catch (NumberFormatException e) {
            return (Integer) ctxt.handleWeirdStringValue(Integer.class, s, "not a quantity");
        }
    }
}

From 08-custom-and-collect.txt:

== exception thrown inside a custom deserializer ==
parseInt left alone : tools.jackson.databind.DatabindException
   path com.ankurm.exceptions.E08CustomAndCollect$A["qty"]
   cause java.lang.NumberFormatException
reported via context: tools.jackson.databind.exc.InvalidFormatException
   path com.ankurm.exceptions.E08CustomAndCollect$B["qty"]

Code that constructed exceptions directly needs a change too. The base classes now have protected constructors; use a factory such as DatabindException.from(parser, message), or better, the context’s report... and handle... methods.

From 09-compile-errors.txt:

=== NewException.java ===
NewException.java:6: error: constructor DatabindException in class DatabindException cannot be applied to given types;
        throw new DatabindException("bad data");
              ^
  required: String
  found:    String
  reason: DatabindException(String) has protected access in DatabindException
NewException.java:10: error: no suitable constructor found for JacksonException(String)
        throw new JacksonException("bad data");
              ^
    constructor JacksonException.JacksonException(String) is not applicable
      (JacksonException(String) has protected access in JacksonException)
    constructor JacksonException.JacksonException(Throwable) is not applicable
      (argument mismatch; String cannot be converted to Throwable)
2 errors

Jackson 3 also has an opt-in way to gather several binding problems in one pass, which suits form-style validation. A normal read stops at the first one.

From E08CustomAndCollect.java:

    MAPPER.readerFor(Order.class).problemCollectingReader().readValueCollectingProblems(bad);
} catch (DeferredBindingException e) {
    System.out.println(e.getClass().getSimpleName() + " with " + e.getProblemCount() + " problems");
    for (CollectedProblem p : e.getProblems()) System.out.println("   " + p.getPath() + "  raw=" + p.getRawValue());

From 08-custom-and-collect.txt:

== collect several problems (ObjectReader.problemCollectingReader) ==
plain readValue stops at the first: com.ankurm.exceptions.Order["id"]
DeferredBindingException with 3 problems
   /id  raw=x
   /quantity  raw=y
   /lines/0/qty  raw=z
Going deeper
  • Custom serializers and mix-ins in Jackson 3.
  • CollectedProblem.getRawValue() returns the rejected value, so the same leak warning applies. The collecting reader exists in 3.1.8 as well as 3.3.0; how it behaves on a syntax error was not tested here.

Spring Boot 4: three places a Jackson exception starts

In a web application the same exception class can mean “the client sent rubbish” or “we are broken”. The difference is where it started. Spring wraps the request and response cases in its own exception types; a call you make yourself is not wrapped.

Where it startsWhat reaches Spring MVCRight statusreading @RequestBodyyour own readValue()writing the responseHttpMessageNotReadableExceptioncause: JacksonExceptionJacksonException(not wrapped)HttpMessageNotWritableExceptioncause: JacksonException400500500@ExceptionHandler also matches causes, so one handler for JacksonExceptionswallows all three rows and gives them the same status.

The demo controller has one endpoint per origin, from OrderController.java:

/** 1. The client's JSON. Spring reads it for you. */
@PostMapping("/orders")
public String create(@RequestBody Order order) {
    return "accepted order " + order.id();
}

/** 2. Data the client never saw (a database column, a file) is corrupt, and your code parses it. */
@GetMapping("/orders/stored")
public Order stored() {
    String corruptRow = "{\"id\": 1, \"quantity\": ";
    return mapper.readValue(corruptRow, Order.class);
}

/** 3. Your object cannot be written. */
@GetMapping("/orders/unwritable")
public Unwritable unwritable() {
    return new Unwritable();
}

Without any advice of your own, Spring Boot 4.2.0 already picks sensible statuses. The bodies say little, which is deliberate.

No @ControllerAdvice, from 20-boot-no-advice.txt:

jackson-databind 3.1.8, spring-boot 4.2.0

== client sends broken JSON
> POST /orders  {"id": 1, "quantity": }
< 400  {"timestamp":"...","status":400,"error":"Bad Request","path":"/orders"}
  log: WARN .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected character ('}' (code 125)): expected a value]

== client sends a wrong type
> POST /orders  {"id":1,"quantity":1,"lines":[{"sku":"A","qty":"two"}]}
< 400  {"timestamp":"...","status":400,"error":"Bad Request","path":"/orders"}
  log: WARN .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `int` from String "two": not a valid `int` value]

== stored data is corrupt (server problem)
> GET /orders/stored
< 500  {"timestamp":"...","status":500,"error":"Internal Server Error","path":"/orders/stored"}
  log: ERROR o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: tools.jackson.core.exc.UnexpectedEndOfInputException: Unexpected end-of-input within/between Object entries

== response cannot be serialised (server problem)
> GET /orders/unwritable
< 500  {"timestamp":"...","status":500,"error":"Internal Server Error","path":"/orders/unwritable"}
  log: WARN .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: lazy collection not initialised]

Then someone adds the obvious handler, reasoning that a JSON error is a bad request:

From NaiveAdvice.java:

@RestControllerAdvice
@Profile("naive")
public class NaiveAdvice {

    @ExceptionHandler(JacksonException.class)
    public ResponseEntity<Map<String, String>> badJson(JacksonException e) {
        return ResponseEntity.badRequest().body(Map.of("error", e.getOriginalMessage()));
    }
}

The same four requests with that handler active, from 21-boot-naive-advice.txt:

jackson-databind 3.1.8, spring-boot 4.2.0

== client sends broken JSON
> POST /orders  {"id": 1, "quantity": }
< 400  {"error":"Unexpected character ('}' (code 125)): expected a value"}

== client sends a wrong type
> POST /orders  {"id":1,"quantity":1,"lines":[{"sku":"A","qty":"two"}]}
< 400  {"error":"Cannot deserialize value of type `int` from String \"two\": not a valid `int` value"}

== stored data is corrupt (server problem)
> GET /orders/stored
< 400  {"error":"Unexpected end-of-input within/between Object entries"}

== response cannot be serialised (server problem)
> GET /orders/unwritable
< 400  {"error":"lazy collection not initialised"}

All four now answer 400. The corrupt database row and the broken getter are reported as the client’s fault, the internal message lazy collection not initialised is sent to them, and no warning or error line was captured for any of the four. The reason is that @ExceptionHandler matches nested causes as well as the thrown type, so the wrapped request and response cases are caught too. Your monitoring sees a rise in 4xx and nothing else.

Do not map JacksonException to 400. Handle HttpMessageNotReadableException for client mistakes and read the Jackson exception from its cause. Treat a bare JacksonException reaching the web layer as a server error, and log it.

The corrected advice, from GoodAdvice.java:

public class GoodAdvice extends ResponseEntityExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GoodAdvice.class);

    @Override
    protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex,
            HttpHeaders headers, HttpStatusCode status, WebRequest request) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(status, "Request body could not be read");
        if (ex.getCause() instanceof JacksonException cause) {
            if (!cause.getPath().isEmpty()) problem.setProperty("field", fieldPath(cause));
            if (cause.getLocation() != null) {
                problem.setProperty("line", cause.getLocation().getLineNr());
                problem.setProperty("column", cause.getLocation().getColumnNr());
            }
        }
        return handleExceptionInternal(ex, problem, headers, status, request);
    }

    @ExceptionHandler(JacksonException.class)
    public ProblemDetail serverSideJson(JacksonException e) {
        log.error("JSON failure inside the application", e);
        return ProblemDetail.forStatus(HttpStatus.INTERNAL_SERVER_ERROR);
    }

From 22-boot-good-advice.txt:

jackson-databind 3.1.8, spring-boot 4.2.0

== client sends broken JSON
> POST /orders  {"id": 1, "quantity": }
< 400  {"detail":"Request body could not be read","status":400,"title":"Bad Request","line":1,"column":23}

== client sends a wrong type
> POST /orders  {"id":1,"quantity":1,"lines":[{"sku":"A","qty":"two"}]}
< 400  {"detail":"Request body could not be read","status":400,"title":"Bad Request","field":"lines[0].qty","line":1,"column":48}

== stored data is corrupt (server problem)
> GET /orders/stored
< 500  {"status":500,"title":"Internal Server Error"}
  log: ERROR com.ankurm.exceptions.boot.GoodAdvice    : JSON failure inside the application

== response cannot be serialised (server problem)
> GET /orders/unwritable
< 500  {"detail":"Failed to write request","status":500,"title":"Internal Server Error"}

ResponseEntityExceptionHandler already handles HttpMessageNotWritableException, and because a match on the thrown type beats a match on its cause within one advice class, the response-writing failure stays a 500 even with the JacksonException handler present. That rule applies within a single class; the Spring reference notes that a cause match in a higher-priority advice wins over an exact match in a lower-priority one.

Calling another service

With RestClient, a response that does not fit your type arrives wrapped twice, so catch RestClientException and inspect the cause chain:

From 24-boot-restclient.txt:

thrown : org.springframework.web.client.RestClientException
cause  : org.springframework.http.converter.HttpMessageNotReadableException
cause  : tools.jackson.databind.exc.InvalidFormatException
How the tests capture these transcripts

The AbstractScenarios.java class starts the app on a random port, sends four requests with the JDK HTTP client, asserts the four status codes and records the WARN and ERROR headline lines. Three subclasses run it with no profile, naive and good.

Going deeper

@Transactional now rolls back where it used to commit

This one involves no catch block at all. By default Spring rolls back for unchecked exceptions and commits for checked ones. A method that wrote a row and then failed to serialise something used to keep the row. After the upgrade it does not.

INSERT, then serialiseINSERT, then serialiseJackson 2 throws (checked)Jackson 3 throws (unchecked)COMMIT: 1 row leftROLLBACK: 0 rowsSame method body, same annotation, different data in the table after the failure.

From AuditService.java:

@Transactional
public String saveWithJackson2() throws com.fasterxml.jackson.core.JsonProcessingException {
    insert("jackson2");
    return jackson2.writeValueAsString(new Unwritable());
}

@Transactional
public String saveWithJackson3() {
    insert("jackson3");
    return jackson3.writeValueAsString(new Unwritable());
}

Rows counted after each call against H2, from 23-boot-transaction-rollback.txt:

@Transactional + Jackson 2 (checked)
   threw com.fasterxml.jackson.databind.JsonMappingException
   rows left in audit: 1
@Transactional + Jackson 3 (unchecked)
   threw tools.jackson.databind.DatabindException
   rows left in audit: 0
@Transactional(noRollbackFor = JacksonException.class)
   threw tools.jackson.databind.DatabindException
   rows left in audit: 1

For most code the new behaviour is what you wanted all along. Where something depends on the row surviving, such as an audit or outbox entry written before a payload is rendered, make it explicit with noRollbackFor, or move that write into its own transaction. The same applies in reverse to any rollbackFor = JsonProcessingException.class you added to get a rollback: after renaming it to JacksonException it is redundant.

Going deeper
  • TransactionAndClientTest.java asserts the three row counts.
  • Retry rules deserve the same review: anything configured to retry on IOException no longer retries a JacksonIOException by type alone. No retry library was run here; this follows from the hierarchy.

Migrating the code: OpenRewrite, a sed script, and what both miss

To measure this, the repository has a small Jackson 2 project with six typical error-handling shapes in OrderCodec.java and five tests that pin their behaviour. Both migration approaches ran on throwaway copies of it, and the same tests were run afterwards.

Jackson 2 project5 / 5 passOpenRewritecompiles, 3 / 5sed renamedoes not compilefix that 1 error2 / 53 hand fixes5 / 5A green compile is not the finish line: the tests found what the compiler could not.

The starting point, from 30-before-jackson2-tests.txt:

[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0 -- in com.ankurm.orders.OrderCodecTest
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

OpenRewrite

OpenRewrite’s UpgradeJackson_2_3 recipe can be run without touching your POM:

The command, as the script runs it, in migrate.sh:

$MVN -B -U org.openrewrite.maven:rewrite-maven-plugin:6.46.1:run \
     -Drewrite.recipeArtifactCoordinates=org.openrewrite.recipe:rewrite-jackson:1.29.0 \
     -Drewrite.activeRecipes=org.openrewrite.java.jackson.UpgradeJackson_2_3

The part of its diff that handles our catch blocks, from 32-openrewrite.diff.txt:

@@ -25,11 +26,11 @@ public class OrderCodec {
         try {
             mapper.readValue(json, Order.class);
             return "ok";
-        } catch (JsonParseException e) {
+        } catch (StreamReadException e) {
             return "not JSON";
-        } catch (JsonMappingException e) {
-            return "bad field " + e.getPath().get(0).getFieldName();
-        } catch (JsonProcessingException e) {
+        } catch (DatabindException e) {
+            return "bad field " + e.getPath().get(0).getPropertyName();
+        } catch (JacksonException e) {
             return "other";
         }
     }
@@ -38,7 +39,7 @@ public class OrderCodec {
     public Order orDefault(String json) {
         try {
             return mapper.readValue(json, Order.class);
-        } catch (IOException e) {
+        } catch (JacksonException e) {
             return new Order(0, 0);
         }
     }
@@ -48,7 +49,7 @@ public class OrderCodec {
         try {
             String json = Files.readString(file);
             return mapper.readValue(json, Order.class);
-        } catch (IOException e) {
+        } catch (JacksonException | IOException e) {
             return new Order(0, 0);
         }
     }

That is better than a rename. It turned catch (IOException e) into catch (JacksonException e) where only Jackson could throw, produced JacksonException | IOException for the block that also reads a file, removed the dead throws JsonProcessingException and updated getFieldName(). It also chose Jackson 3.1.9 in the POM. The result compiles. The tests then say:

From 33-openrewrite-tests.txt:

[ERROR] Tests run: 5, Failures: 0, Errors: 2, Skipped: 0 <<< FAILURE! -- in com.ankurm.orders.OrderCodecTest
[ERROR]   OrderCodecTest.callerRejectsBadStream:39 » StreamRead Unexpected character ('}' (code 125)): expected a value
[ERROR]   OrderCodecTest.rejectsBadMap:44 » InvalidFormat Cannot deserialize value of type `long` from String "abc": not a valid `long` value
[ERROR] Tests run: 5, Failures: 0, Errors: 2, Skipped: 0
[INFO] BUILD FAILURE

The two survivors are the ones that need meaning, not syntax. read(InputStream) still declares throws IOException, so its caller’s catch (IOException e) still compiles and no longer sees bad JSON. And convertValue is still guarded by catch (IllegalArgumentException e).

A text substitution

If you cannot run OpenRewrite, a short sed script handles the names:

The Java substitutions, from migrate-regex.sh:

find "$1" -name '*.java' -print0 | xargs -0 sed -i -E \
  -e 's/com\.fasterxml\.jackson\.core\.JsonProcessingException/tools.jackson.core.JacksonException/g' \
  -e 's/com\.fasterxml\.jackson\.core\.JsonParseException/tools.jackson.core.exc.StreamReadException/g' \
  -e 's/com\.fasterxml\.jackson\.core\.JsonGenerationException/tools.jackson.core.exc.StreamWriteException/g' \
  -e 's/com\.fasterxml\.jackson\.core\.io\.JsonEOFException/tools.jackson.core.exc.UnexpectedEndOfInputException/g' \
  -e 's/com\.fasterxml\.jackson\.databind\.JsonMappingException/tools.jackson.databind.DatabindException/g' \
  -e 's/com\.fasterxml\.jackson\.(core|databind|dataformat|datatype|module)/tools.jackson.\1/g' \
  -e 's/\bJsonProcessingException\b/JacksonException/g' \
  -e 's/\bJsonParseException\b/StreamReadException/g' \
  -e 's/\bJsonGenerationException\b/StreamWriteException/g' \
  -e 's/\bJsonEOFException\b/UnexpectedEndOfInputException/g' \
  -e 's/\bJsonMappingException\b/DatabindException/g' \
  -e 's/\.getFieldName\(\)/.getPropertyName()/g'

It stops at the one place the compiler can see, from 34-regex.txt:

$ scripts/migrate-regex.sh <copy>; mvn test
[ERROR] <work>/regex/src/main/java/com/ankurm/orders/OrderCodec.java:[41,11] exception java.io.IOException is never thrown in body of corresponding try statement
[INFO] BUILD FAILURE

Fix only that error, and the build is green enough to run the tests, from 35-regex-after-compile-fix.txt:

$ # after fixing the single compile error (orDefault now catches JacksonException)
[ERROR] Tests run: 5, Failures: 0, Errors: 3, Skipped: 0 <<< FAILURE! -- in com.ankurm.orders.OrderCodecTest
[ERROR]   OrderCodecTest.callerRejectsBadStream:39 » StreamRead Unexpected character ('}' (code 125)): expected a value
[ERROR]   OrderCodecTest.fallsBackOnBadFile:34 » StreamRead Unexpected character ('}' (code 125)): expected a value
[ERROR]   OrderCodecTest.rejectsBadMap:44 » InvalidFormat Cannot deserialize value of type `long` from String "abc": not a valid `long` value
[ERROR] Tests run: 5, Failures: 0, Errors: 3, Skipped: 0
[INFO] BUILD FAILURE

Three failures instead of two: the extra one is the file-plus-parse block, the silent trap from earlier, which OpenRewrite had handled. The review script lists the candidates a human must read:

From 34-regex.txt:

$ scripts/review-catches.sh <copy>
-- catch/throws IOException in files that touch Jackson (or its wrappers)
src/main/java/com/ankurm/orders/Importer.java:15:        } catch (IOException e) {
src/main/java/com/ankurm/orders/OrderCodec.java:41:        } catch (IOException e) {
src/main/java/com/ankurm/orders/OrderCodec.java:51:        } catch (IOException e) {
src/main/java/com/ankurm/orders/OrderCodec.java:57:    public Order read(InputStream in) throws IOException {
src/test/java/com/ankurm/orders/OrderCodecTest.java:32:    void fallsBackOnBadFile(@TempDir Path dir) throws IOException {
-- catch IllegalArgumentException (convertValue no longer wraps)
src/main/java/com/ankurm/orders/OrderCodec.java:66:        } catch (IllegalArgumentException e) {
-- generic catches that now also receive Jackson errors
(none)

The three hand fixes

On top of the OpenRewrite output, from OrderCodec.java:

    /** 5. FIX: dropped "throws IOException", so callers can no longer believe it covers bad JSON */
    public Order read(InputStream in) {
        return mapper.readValue(in, Order.class);
    }

    /** 6. FIX: convertValue now throws a JacksonException, not IllegalArgumentException */
    public boolean isOrder(Map<String, Object> map) {
        try {
            mapper.convertValue(map, Order.class);
            return true;
        } catch (JacksonException e) {
            return false;
        }
    }
}

and the caller, in Importer.java:

    public String importOne(String json) {
        try (var in = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8))) {
            return "imported " + codec.read(in).id();
        } catch (IOException | JacksonException e) {
            return "rejected";
        }
    }
}

Result, from 36-after-hand-fixes-tests.txt:

[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0 -- in com.ankurm.orders.OrderCodecTest
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
Write the failure tests before you migrate. The two (or three) regressions above are found only because tests fed bad input to each handler while the project was still on Jackson 2. A suite that only covers valid JSON passes once any of these migrations compiles.

The sed script also edits the POM; read it whole first. It assumes GNU sed, a literal 2.23.0 version and a single Jackson artifact. Real builds use a BOM or properties. The full OpenRewrite change report and diff are in the repository.

Going deeper

A migration order that works

  1. On Jackson 2, add a bad-input test for every catch that surrounds a mapper call, including callers of methods that declare throws IOException.
  2. Run OpenRewrite (or the substitutions) on a branch.
  3. Fix compile errors, then run those tests.
  4. Grep for IOException, IllegalArgumentException and broad RuntimeException catches near Jackson.
  5. Review @ControllerAdvice mappings, @Transactional methods that serialise after writing, and retry rules.
  6. Check which Jackson 3.x line your Spring Boot version manages before relying on a default.
Should you catch JacksonException everywhere now that nothing forces you to? No. Adding a catch to every call recreates the checked-exception noise with less compiler help. Catch at the few places that can answer: the web boundary, a per-record loop, a message listener that must decide between retry and dead-letter. Everywhere else, let it fly, and make sure something at the top logs it as what it is.

Run it yourself with ./scripts/run-all.sh in the module (JDK 25, Maven, git and GNU sed), which regenerates every file in output/. The script is run-all.sh. What was not run: Gradle builds, WebFlux, Kotlin, and Jackson modules other than databind.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.