exceptions: Jackson 3 unchecked JacksonException hierarchy, Spring Boot 4.2 error handling, OpenRewrite and sed migration
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b4HkWoC7hLzk61vZa8
This commit is contained in:
@@ -42,6 +42,7 @@ mvn -q exec:java -Dexec.mainClass=com.ankurm.jackson3.part5polymorphic.F01Serial
|
|||||||
| [Streaming API & JsonNode — the 1 GiB benchmark](https://ankurm.com/jackson-streaming-api-jsonnode/) | [`streaming-huge-json`](streaming-huge-json) (standalone module, JDK 25, Jackson 3.2.4) | [GenerateHugeJson](streaming-huge-json/src/main/java/com/ankurm/jackson3/streaminghuge/GenerateHugeJson.java) [Scan](streaming-huge-json/src/main/java/com/ankurm/jackson3/streaminghuge/Scan.java) [NestedTrap](streaming-huge-json/src/main/java/com/ankurm/jackson3/streaminghuge/NestedTrap.java) [TruncatedFile](streaming-huge-json/src/main/java/com/ankurm/jackson3/streaminghuge/TruncatedFile.java) [ReadLimits](streaming-huge-json/src/main/java/com/ankurm/jackson3/streaminghuge/ReadLimits.java) | [README](streaming-huge-json/README.md), [output/](streaming-huge-json/output) |
|
| [Streaming API & JsonNode — the 1 GiB benchmark](https://ankurm.com/jackson-streaming-api-jsonnode/) | [`streaming-huge-json`](streaming-huge-json) (standalone module, JDK 25, Jackson 3.2.4) | [GenerateHugeJson](streaming-huge-json/src/main/java/com/ankurm/jackson3/streaminghuge/GenerateHugeJson.java) [Scan](streaming-huge-json/src/main/java/com/ankurm/jackson3/streaminghuge/Scan.java) [NestedTrap](streaming-huge-json/src/main/java/com/ankurm/jackson3/streaminghuge/NestedTrap.java) [TruncatedFile](streaming-huge-json/src/main/java/com/ankurm/jackson3/streaminghuge/TruncatedFile.java) [ReadLimits](streaming-huge-json/src/main/java/com/ankurm/jackson3/streaminghuge/ReadLimits.java) | [README](streaming-huge-json/README.md), [output/](streaming-huge-json/output) |
|
||||||
| [ObjectMapper and JsonMapper (Jackson 2 and 3)](https://ankurm.com/jackson-objectmapper-guide/) | [`objectmapper-jsonmapper`](objectmapper-jsonmapper) (standalone module, JDK 25, Jackson 3.3.0 and 2.23.0 side by side) | [P01](objectmapper-jsonmapper/src/main/java/com/ankurm/objectmapper/P01TwoMappersSideBySide.java) [P02](objectmapper-jsonmapper/src/main/java/com/ankurm/objectmapper/P02ImmutableMapper.java) [P03](objectmapper-jsonmapper/src/main/java/com/ankurm/objectmapper/P03ReadWriteCookbook.java) [P04](objectmapper-jsonmapper/src/main/java/com/ankurm/objectmapper/P04ConfigRecipes.java) [P05](objectmapper-jsonmapper/src/main/java/com/ankurm/objectmapper/P05JavaTime.java) [P06](objectmapper-jsonmapper/src/main/java/com/ankurm/objectmapper/P06Exceptions.java) [P07](objectmapper-jsonmapper/src/main/java/com/ankurm/objectmapper/P07SharedMapperThreads.java) | [README](objectmapper-jsonmapper/README.md), [output/](objectmapper-jsonmapper/output) |
|
| [ObjectMapper and JsonMapper (Jackson 2 and 3)](https://ankurm.com/jackson-objectmapper-guide/) | [`objectmapper-jsonmapper`](objectmapper-jsonmapper) (standalone module, JDK 25, Jackson 3.3.0 and 2.23.0 side by side) | [P01](objectmapper-jsonmapper/src/main/java/com/ankurm/objectmapper/P01TwoMappersSideBySide.java) [P02](objectmapper-jsonmapper/src/main/java/com/ankurm/objectmapper/P02ImmutableMapper.java) [P03](objectmapper-jsonmapper/src/main/java/com/ankurm/objectmapper/P03ReadWriteCookbook.java) [P04](objectmapper-jsonmapper/src/main/java/com/ankurm/objectmapper/P04ConfigRecipes.java) [P05](objectmapper-jsonmapper/src/main/java/com/ankurm/objectmapper/P05JavaTime.java) [P06](objectmapper-jsonmapper/src/main/java/com/ankurm/objectmapper/P06Exceptions.java) [P07](objectmapper-jsonmapper/src/main/java/com/ankurm/objectmapper/P07SharedMapperThreads.java) | [README](objectmapper-jsonmapper/README.md), [output/](objectmapper-jsonmapper/output) |
|
||||||
| [JavaTimeModule in Jackson 3](https://ankurm.com/jackson-3-javatimemodule-java-time-date-formats/) | [`java-time`](java-time) (standalone module, JDK 25, Jackson 3.3.0 and 2.23.0, plus Spring Boot 4.2.0) | [T01..T11](java-time/src/main/java/com/ankurm/javatime), [Boot app](java-time/boot) | [README](java-time/README.md), [output/](java-time/output) |
|
| [JavaTimeModule in Jackson 3](https://ankurm.com/jackson-3-javatimemodule-java-time-date-formats/) | [`java-time`](java-time) (standalone module, JDK 25, Jackson 3.3.0 and 2.23.0, plus Spring Boot 4.2.0) | [T01..T11](java-time/src/main/java/com/ankurm/javatime), [Boot app](java-time/boot) | [README](java-time/README.md), [output/](java-time/output) |
|
||||||
|
| [JsonProcessingException in Jackson 3](https://ankurm.com/jackson-3-jsonprocessingexception-jacksonexception/) | [`exceptions`](exceptions) (standalone module, JDK 25, Jackson 3.3.0 and 2.23.0, Spring Boot 4.2.0) | [E01-E09](exceptions/src/main/java/com/ankurm/exceptions), [boot](exceptions/boot), [migration](exceptions/migration) | [README](exceptions/README.md), [output/](exceptions/output) |
|
||||||
| [Security Best Practices](https://ankurm.com/jackson-security-best-practices/) | [`part7security`](src/main/java/com/ankurm/jackson3/part7security) | [H01](src/main/java/com/ankurm/jackson3/part7security/H01SafePolymorphismByAnnotation.java) [H02](src/main/java/com/ankurm/jackson3/part7security/H02DefaultTypingRemoved.java) [H03](src/main/java/com/ankurm/jackson3/part7security/H03PolymorphicTypeValidatorAllowlist.java) [H04](src/main/java/com/ankurm/jackson3/part7security/H04StreamReadConstraints.java) [H05](src/main/java/com/ankurm/jackson3/part7security/H05NeverDeserialiseIntoObject.java) | [write-up](docs/part7-security.md) |
|
| [Security Best Practices](https://ankurm.com/jackson-security-best-practices/) | [`part7security`](src/main/java/com/ankurm/jackson3/part7security) | [H01](src/main/java/com/ankurm/jackson3/part7security/H01SafePolymorphismByAnnotation.java) [H02](src/main/java/com/ankurm/jackson3/part7security/H02DefaultTypingRemoved.java) [H03](src/main/java/com/ankurm/jackson3/part7security/H03PolymorphicTypeValidatorAllowlist.java) [H04](src/main/java/com/ankurm/jackson3/part7security/H04StreamReadConstraints.java) [H05](src/main/java/com/ankurm/jackson3/part7security/H05NeverDeserialiseIntoObject.java) | [write-up](docs/part7-security.md) |
|
||||||
| — (beyond the posts) | [`beyond`](src/main/java/com/ankurm/jackson3/beyond) | [Y01](src/main/java/com/ankurm/jackson3/beyond/Y01UncheckedExceptions.java) [Y02](src/main/java/com/ankurm/jackson3/beyond/Y02TrailingTokens.java) [Y03](src/main/java/com/ankurm/jackson3/beyond/Y03DateTimeDefaults.java) [Y04](src/main/java/com/ankurm/jackson3/beyond/Y04ImmutableMapperAndReaders.java) [Y05](src/main/java/com/ankurm/jackson3/beyond/Y05CreatorDetection.java) [Y06](src/main/java/com/ankurm/jackson3/beyond/Y06RecyclerPoolTuning.java) | [write-up](docs/beyond.md) |
|
| — (beyond the posts) | [`beyond`](src/main/java/com/ankurm/jackson3/beyond) | [Y01](src/main/java/com/ankurm/jackson3/beyond/Y01UncheckedExceptions.java) [Y02](src/main/java/com/ankurm/jackson3/beyond/Y02TrailingTokens.java) [Y03](src/main/java/com/ankurm/jackson3/beyond/Y03DateTimeDefaults.java) [Y04](src/main/java/com/ankurm/jackson3/beyond/Y04ImmutableMapperAndReaders.java) [Y05](src/main/java/com/ankurm/jackson3/beyond/Y05CreatorDetection.java) [Y06](src/main/java/com/ankurm/jackson3/beyond/Y06RecyclerPoolTuning.java) | [write-up](docs/beyond.md) |
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# exceptions: Jackson 3 errors, unchecked
|
||||||
|
|
||||||
|
Companion code for
|
||||||
|
[JsonProcessingException Is Gone in Jackson 3](https://ankurm.com/jackson-3-jsonprocessingexception-jacksonexception/).
|
||||||
|
The explanations are in the article; this folder holds the code and its captured output.
|
||||||
|
|
||||||
|
Verified with Temurin 25.0.5.1, Jackson 3.3.0 and 2.23.0 (3.1.8 and 3.2.4 for one comparison),
|
||||||
|
Spring Boot 4.2.0 (which manages Jackson 3.1.8), rewrite-maven-plugin 6.46.1 with rewrite-jackson 1.29.0.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./scripts/run-all.sh # regenerates every file in output/ (needs JDK 25, Maven, git, GNU sed)
|
||||||
|
```
|
||||||
|
|
||||||
|
| Path | What it is |
|
||||||
|
|---|---|
|
||||||
|
| `src/main/java` | `E01`-`E09`: hierarchy, triggers, silent catch, J2/J3 differences, location, stack traces, handling, custom deserializers, missing primitives |
|
||||||
|
| `src/broken` | files that must not compile; `scripts/broken.sh` records javac's message |
|
||||||
|
| `boot/` | Spring Boot 4.2.0 app and tests: no advice, naive advice, corrected advice, `@Transactional` rollback, `RestClient` |
|
||||||
|
| `migration/before` | a small Jackson 2 project with five behaviour tests |
|
||||||
|
| `migration/after` | the OpenRewrite result plus three hand fixes (marked `FIX`) |
|
||||||
|
| `scripts/migrate.sh` | runs OpenRewrite and a sed script on copies, records diffs and test results |
|
||||||
|
| `output/` | `0x` plain Java, `2x` Spring Boot, `3x` migration |
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
|
<version>4.2.0</version>
|
||||||
|
<relativePath/>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<groupId>com.ankurm</groupId>
|
||||||
|
<artifactId>jackson-exceptions-boot</artifactId>
|
||||||
|
<version>1.0.0</version>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<java.version>25</java.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<!-- No Jackson version is declared: Boot 4.2.0 chooses it. The tests print what that is. -->
|
||||||
|
<dependencies>
|
||||||
|
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webmvc</artifactId></dependency>
|
||||||
|
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-restclient</artifactId></dependency>
|
||||||
|
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency>
|
||||||
|
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><scope>runtime</scope></dependency>
|
||||||
|
<!-- Jackson 2 only so the @Transactional test can show the old behaviour next to the new one -->
|
||||||
|
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId></dependency>
|
||||||
|
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package com.ankurm.exceptions.boot;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Insert a row, then fail while serialising. Spring rolls back on unchecked exceptions by default
|
||||||
|
* and commits on checked ones, so the Jackson upgrade changes what is left in the table.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class AuditService {
|
||||||
|
|
||||||
|
private final JdbcClient jdbc;
|
||||||
|
private final com.fasterxml.jackson.databind.ObjectMapper jackson2 = new com.fasterxml.jackson.databind.ObjectMapper();
|
||||||
|
private final tools.jackson.databind.json.JsonMapper jackson3 = tools.jackson.databind.json.JsonMapper.builder().build();
|
||||||
|
|
||||||
|
public AuditService(JdbcClient jdbc) {
|
||||||
|
this.jdbc = jdbc;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class Unwritable {
|
||||||
|
public String getName() {
|
||||||
|
throw new IllegalStateException("lazy collection not initialised");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@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());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The Jackson 3 way to keep the old commit-anyway behaviour, if something really depends on it. */
|
||||||
|
@Transactional(noRollbackFor = tools.jackson.core.JacksonException.class)
|
||||||
|
public String saveWithJackson3NoRollback() {
|
||||||
|
insert("jackson3-noRollbackFor");
|
||||||
|
return jackson3.writeValueAsString(Map.of("x", new Unwritable()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void insert(String who) {
|
||||||
|
jdbc.sql("insert into audit(source) values (?)").param(who).update();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package com.ankurm.exceptions.boot;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class BootApp {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(BootApp.class, args);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package com.ankurm.exceptions.boot;
|
||||||
|
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.context.annotation.Profile;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.HttpStatusCode;
|
||||||
|
import org.springframework.http.ProblemDetail;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||||
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||||
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
|
import org.springframework.web.context.request.WebRequest;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
|
||||||
|
import tools.jackson.core.JacksonException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Client mistakes arrive wrapped in HttpMessageNotReadableException: handle that type.
|
||||||
|
* A JacksonException that reaches the web layer by itself is a server problem.
|
||||||
|
*/
|
||||||
|
@RestControllerAdvice
|
||||||
|
@Profile("good")
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Names and indexes only: no values, no class names. */
|
||||||
|
static String fieldPath(JacksonException e) {
|
||||||
|
return e.getPath().stream()
|
||||||
|
.map(r -> r.getPropertyName() != null ? "." + r.getPropertyName() : "[" + r.getIndex() + "]")
|
||||||
|
.collect(Collectors.joining())
|
||||||
|
.replaceFirst("^\\.", "");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package com.ankurm.exceptions.boot;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import org.springframework.context.annotation.Profile;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||||
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
|
import tools.jackson.core.JacksonException;
|
||||||
|
|
||||||
|
/** The tempting one-liner: "it is a JSON problem, so it is a 400". Profile "naive" only. */
|
||||||
|
@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()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.ankurm.exceptions.boot;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record Order(long id, int quantity, List<Line> lines) {
|
||||||
|
public record Line(String sku, int qty) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package com.ankurm.exceptions.boot;
|
||||||
|
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
|
|
||||||
|
/** Three places a Jackson 3 exception can start: the request body, your own code, and the response body. */
|
||||||
|
@RestController
|
||||||
|
public class OrderController {
|
||||||
|
|
||||||
|
private final JsonMapper mapper;
|
||||||
|
|
||||||
|
public OrderController(JsonMapper mapper) {
|
||||||
|
this.mapper = mapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class Unwritable {
|
||||||
|
public String getName() {
|
||||||
|
throw new IllegalStateException("lazy collection not initialised");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stand-ins for a remote service, used by the RestClient test. */
|
||||||
|
@GetMapping(value = "/upstream/wrong-type", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||||
|
public String upstreamWrongType() {
|
||||||
|
return "{\"id\":\"abc\",\"quantity\":1}";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
spring.main.banner-mode=off
|
||||||
|
spring.sql.init.mode=always
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
create table if not exists audit (id bigint generated always as identity primary key, source varchar(60));
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package com.ankurm.exceptions.boot;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.springframework.boot.test.system.CapturedOutput;
|
||||||
|
import org.springframework.boot.test.system.OutputCaptureExtension;
|
||||||
|
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
/** The same four requests, run against: no advice, the naive advice, the good advice. */
|
||||||
|
@ExtendWith(OutputCaptureExtension.class)
|
||||||
|
abstract class AbstractScenarios {
|
||||||
|
|
||||||
|
@LocalServerPort
|
||||||
|
int port;
|
||||||
|
|
||||||
|
abstract String file();
|
||||||
|
|
||||||
|
/** Expected status of the four requests, in order. */
|
||||||
|
abstract List<Integer> expected();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void fourRequests(CapturedOutput output) throws Exception {
|
||||||
|
var t = new Transcript();
|
||||||
|
t.line("jackson-databind " + tools.jackson.databind.cfg.PackageVersion.VERSION
|
||||||
|
+ ", spring-boot " + org.springframework.boot.SpringBootVersion.getVersion());
|
||||||
|
var statuses = new ArrayList<Integer>();
|
||||||
|
statuses.add(step(t, output, "client sends broken JSON", "POST", "/orders", "{\"id\": 1, \"quantity\": }"));
|
||||||
|
statuses.add(step(t, output, "client sends a wrong type", "POST", "/orders",
|
||||||
|
"{\"id\":1,\"quantity\":1,\"lines\":[{\"sku\":\"A\",\"qty\":\"two\"}]}"));
|
||||||
|
statuses.add(step(t, output, "stored data is corrupt (server problem)", "GET", "/orders/stored", null));
|
||||||
|
statuses.add(step(t, output, "response cannot be serialised (server problem)", "GET", "/orders/unwritable", null));
|
||||||
|
t.write(file());
|
||||||
|
assertThat(statuses).isEqualTo(expected());
|
||||||
|
}
|
||||||
|
|
||||||
|
private int step(Transcript t, CapturedOutput output, String title, String method, String path, String body) throws Exception {
|
||||||
|
int before = output.getAll().length();
|
||||||
|
t.line("");
|
||||||
|
t.line("== " + title);
|
||||||
|
int status = t.call(port, method, path, body);
|
||||||
|
Thread.sleep(300);
|
||||||
|
t.logLines(output.getAll().substring(before));
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package com.ankurm.exceptions.boot;
|
||||||
|
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
|
||||||
|
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||||
|
class DefaultHandlingTest extends AbstractScenarios {
|
||||||
|
String file() { return "20-boot-no-advice.txt"; }
|
||||||
|
java.util.List<Integer> expected() { return java.util.List.of(400, 400, 500, 500); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package com.ankurm.exceptions.boot;
|
||||||
|
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
|
||||||
|
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||||
|
@ActiveProfiles("good")
|
||||||
|
class GoodAdviceTest extends AbstractScenarios {
|
||||||
|
String file() { return "22-boot-good-advice.txt"; }
|
||||||
|
java.util.List<Integer> expected() { return java.util.List.of(400, 400, 500, 500); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package com.ankurm.exceptions.boot;
|
||||||
|
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
|
||||||
|
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||||
|
@ActiveProfiles("naive")
|
||||||
|
class NaiveAdviceTest extends AbstractScenarios {
|
||||||
|
String file() { return "21-boot-naive-advice.txt"; }
|
||||||
|
java.util.List<Integer> expected() { return java.util.List.of(400, 400, 400, 400); }
|
||||||
|
}
|
||||||
+61
@@ -0,0 +1,61 @@
|
|||||||
|
package com.ankurm.exceptions.boot;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||||
|
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||||
|
import org.springframework.web.client.RestClient;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||||
|
class TransactionAndClientTest {
|
||||||
|
|
||||||
|
@Autowired AuditService audit;
|
||||||
|
@Autowired JdbcClient jdbc;
|
||||||
|
@Autowired RestClient.Builder builder;
|
||||||
|
@LocalServerPort int port;
|
||||||
|
|
||||||
|
interface Call { void run() throws Exception; }
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rollbackRulesFollowTheExceptionType() {
|
||||||
|
var t = new Transcript();
|
||||||
|
attempt(t, "@Transactional + Jackson 2 (checked)", "jackson2", audit::saveWithJackson2);
|
||||||
|
attempt(t, "@Transactional + Jackson 3 (unchecked)", "jackson3", audit::saveWithJackson3);
|
||||||
|
attempt(t, "@Transactional(noRollbackFor = JacksonException.class)", "jackson3-noRollbackFor", audit::saveWithJackson3NoRollback);
|
||||||
|
t.write("23-boot-transaction-rollback.txt");
|
||||||
|
assertThat(rows("jackson2")).isEqualTo(1);
|
||||||
|
assertThat(rows("jackson3")).isZero();
|
||||||
|
assertThat(rows("jackson3-noRollbackFor")).isEqualTo(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void attempt(Transcript t, String title, String source, Call call) {
|
||||||
|
t.line(title);
|
||||||
|
try {
|
||||||
|
call.run();
|
||||||
|
} catch (Exception e) {
|
||||||
|
t.line(" threw " + e.getClass().getName());
|
||||||
|
}
|
||||||
|
t.line(" rows left in audit: " + rows(source));
|
||||||
|
}
|
||||||
|
|
||||||
|
private int rows(String source) {
|
||||||
|
return jdbc.sql("select count(*) from audit where source = ?").param(source).query(Integer.class).single();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void restClientWrapsTheJacksonException() {
|
||||||
|
var t = new Transcript();
|
||||||
|
var client = builder.baseUrl("http://localhost:" + port).build();
|
||||||
|
try {
|
||||||
|
client.get().uri("/upstream/wrong-type").retrieve().body(Order.class);
|
||||||
|
} catch (Exception e) {
|
||||||
|
for (Throwable x = e; x != null; x = x.getCause()) {
|
||||||
|
t.line((x == e ? "thrown : " : "cause : ") + x.getClass().getName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.write("24-boot-restclient.txt");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package com.ankurm.exceptions.boot;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.UncheckedIOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
/** Writes the files under ../output/ that the article quotes. */
|
||||||
|
final class Transcript {
|
||||||
|
private final StringBuilder text = new StringBuilder();
|
||||||
|
|
||||||
|
void line(String s) {
|
||||||
|
text.append(s).append('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
int call(int port, String method, String path, String body) throws Exception {
|
||||||
|
var request = HttpRequest.newBuilder(URI.create("http://localhost:" + port + path))
|
||||||
|
.header("Content-Type", "application/json")
|
||||||
|
.method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(body))
|
||||||
|
.build();
|
||||||
|
try (var client = HttpClient.newHttpClient()) {
|
||||||
|
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||||
|
line("> " + method + " " + path + (body == null ? "" : " " + body));
|
||||||
|
line("< " + response.statusCode() + " " + response.body().replaceAll("\"timestamp\":\"[^\"]+\"", "\"timestamp\":\"...\""));
|
||||||
|
return response.statusCode();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The WARN/ERROR headline lines Spring logged, without timestamps and thread names. */
|
||||||
|
void logLines(CharSequence log) {
|
||||||
|
log.toString().lines()
|
||||||
|
.filter(l -> l.contains(" WARN ") || l.contains(" ERROR "))
|
||||||
|
.map(l -> l.replaceFirst("^.*? (WARN|ERROR) \\d+ --- (\\[[^\\]]*\\] )+", "$1 "))
|
||||||
|
.map(l -> l.length() > 330 ? l.substring(0, 330) + " ..." : l)
|
||||||
|
.forEach(l -> line(" log: " + l));
|
||||||
|
}
|
||||||
|
|
||||||
|
void write(String name) {
|
||||||
|
try {
|
||||||
|
Path dir = Path.of("..", "output");
|
||||||
|
Files.createDirectories(dir);
|
||||||
|
Files.writeString(dir.resolve(name), text.toString());
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<!-- A small, ordinary Jackson 2 codebase. The migration scripts work on a COPY of it. -->
|
||||||
|
<groupId>com.ankurm</groupId>
|
||||||
|
<artifactId>orders-jackson2</artifactId>
|
||||||
|
<version>1.0.0</version>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<maven.compiler.release>25</maven.compiler.release>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>tools.jackson.core</groupId>
|
||||||
|
<artifactId>jackson-databind</artifactId>
|
||||||
|
<version>3.1.9</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter</artifactId>
|
||||||
|
<version>6.1.3</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>3.6.0</version>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package com.ankurm.orders;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import tools.jackson.core.JacksonException;
|
||||||
|
|
||||||
|
/** FIX: catches JacksonException; IOException stays only for the stream's close(). */
|
||||||
|
public class Importer {
|
||||||
|
|
||||||
|
private final OrderCodec codec = new OrderCodec();
|
||||||
|
|
||||||
|
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";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
package com.ankurm.orders;
|
||||||
|
|
||||||
|
public record Order(long id, int quantity) {}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package com.ankurm.orders;
|
||||||
|
|
||||||
|
import tools.jackson.databind.ObjectMapper;
|
||||||
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Map;
|
||||||
|
import tools.jackson.core.JacksonException;
|
||||||
|
import tools.jackson.core.exc.StreamReadException;
|
||||||
|
import tools.jackson.databind.DatabindException;
|
||||||
|
|
||||||
|
/** The OpenRewrite output, plus the two hand fixes marked FIX. */
|
||||||
|
public class OrderCodec {
|
||||||
|
|
||||||
|
private final ObjectMapper mapper = new JsonMapper();
|
||||||
|
|
||||||
|
/** 1. declare it */
|
||||||
|
public Order parse(String json) {
|
||||||
|
return mapper.readValue(json, Order.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 2. catch the subtypes, most specific first */
|
||||||
|
public String diagnose(String json) {
|
||||||
|
try {
|
||||||
|
mapper.readValue(json, Order.class);
|
||||||
|
return "ok";
|
||||||
|
} catch (StreamReadException e) {
|
||||||
|
return "not JSON";
|
||||||
|
} catch (DatabindException e) {
|
||||||
|
return "bad field " + e.getPath().get(0).getPropertyName();
|
||||||
|
} catch (JacksonException e) {
|
||||||
|
return "other";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 3. catch IOException around a call that only Jackson can fail */
|
||||||
|
public Order orDefault(String json) {
|
||||||
|
try {
|
||||||
|
return mapper.readValue(json, Order.class);
|
||||||
|
} catch (JacksonException e) {
|
||||||
|
return new Order(0, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 4. one catch for the file read and the parse */
|
||||||
|
public Order load(Path file) {
|
||||||
|
try {
|
||||||
|
String json = Files.readString(file);
|
||||||
|
return mapper.readValue(json, Order.class);
|
||||||
|
} catch (JacksonException | IOException e) {
|
||||||
|
return new Order(0, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package com.ankurm.orders;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
|
/** Pins the behaviour before the upgrade. The migrated copy has to pass the same assertions. */
|
||||||
|
class OrderCodecTest {
|
||||||
|
|
||||||
|
static final String BAD = "{\"id\": 1, \"quantity\": }";
|
||||||
|
|
||||||
|
final OrderCodec codec = new OrderCodec();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void diagnoses() {
|
||||||
|
assertEquals("not JSON", codec.diagnose(BAD));
|
||||||
|
assertEquals("bad field quantity", codec.diagnose("{\"id\":1,\"quantity\":\"two\"}"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void fallsBackOnBadText() {
|
||||||
|
assertEquals(new Order(0, 0), codec.orDefault(BAD));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void fallsBackOnBadFile(@TempDir Path dir) throws IOException {
|
||||||
|
Path file = Files.writeString(dir.resolve("order.json"), BAD);
|
||||||
|
assertEquals(new Order(0, 0), codec.load(file));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void callerRejectsBadStream() {
|
||||||
|
assertEquals("rejected", new Importer().importOne(BAD));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsBadMap() {
|
||||||
|
assertFalse(codec.isOrder(Map.of("id", "abc")));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<!-- A small, ordinary Jackson 2 codebase. The migration scripts work on a COPY of it. -->
|
||||||
|
<groupId>com.ankurm</groupId>
|
||||||
|
<artifactId>orders-jackson2</artifactId>
|
||||||
|
<version>1.0.0</version>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<maven.compiler.release>25</maven.compiler.release>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
|
<artifactId>jackson-databind</artifactId>
|
||||||
|
<version>2.23.0</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter</artifactId>
|
||||||
|
<version>6.1.3</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>3.6.0</version>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package com.ankurm.orders;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
|
||||||
|
/** A caller that sits above OrderCodec.read and trusts its throws clause. */
|
||||||
|
public class Importer {
|
||||||
|
|
||||||
|
private final OrderCodec codec = new OrderCodec();
|
||||||
|
|
||||||
|
public String importOne(String json) {
|
||||||
|
try (var in = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8))) {
|
||||||
|
return "imported " + codec.read(in).id();
|
||||||
|
} catch (IOException e) {
|
||||||
|
return "rejected";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
package com.ankurm.orders;
|
||||||
|
|
||||||
|
public record Order(long id, int quantity) {}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package com.ankurm.orders;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.JsonParseException;
|
||||||
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
|
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/** Six common ways Jackson 2 code deals with failure. */
|
||||||
|
public class OrderCodec {
|
||||||
|
|
||||||
|
private final ObjectMapper mapper = new ObjectMapper();
|
||||||
|
|
||||||
|
/** 1. declare it */
|
||||||
|
public Order parse(String json) throws JsonProcessingException {
|
||||||
|
return mapper.readValue(json, Order.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 2. catch the subtypes, most specific first */
|
||||||
|
public String diagnose(String json) {
|
||||||
|
try {
|
||||||
|
mapper.readValue(json, Order.class);
|
||||||
|
return "ok";
|
||||||
|
} catch (JsonParseException e) {
|
||||||
|
return "not JSON";
|
||||||
|
} catch (JsonMappingException e) {
|
||||||
|
return "bad field " + e.getPath().get(0).getFieldName();
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
return "other";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 3. catch IOException around a call that only Jackson can fail */
|
||||||
|
public Order orDefault(String json) {
|
||||||
|
try {
|
||||||
|
return mapper.readValue(json, Order.class);
|
||||||
|
} catch (IOException e) {
|
||||||
|
return new Order(0, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 4. one catch for the file read and the parse */
|
||||||
|
public Order load(Path file) {
|
||||||
|
try {
|
||||||
|
String json = Files.readString(file);
|
||||||
|
return mapper.readValue(json, Order.class);
|
||||||
|
} catch (IOException e) {
|
||||||
|
return new Order(0, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 5. the caller was told to expect IOException */
|
||||||
|
public Order read(InputStream in) throws IOException {
|
||||||
|
return mapper.readValue(in, Order.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 6. convertValue reported problems as IllegalArgumentException */
|
||||||
|
public boolean isOrder(Map<String, Object> map) {
|
||||||
|
try {
|
||||||
|
mapper.convertValue(map, Order.class);
|
||||||
|
return true;
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package com.ankurm.orders;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
|
/** Pins the behaviour before the upgrade. The migrated copy has to pass the same assertions. */
|
||||||
|
class OrderCodecTest {
|
||||||
|
|
||||||
|
static final String BAD = "{\"id\": 1, \"quantity\": }";
|
||||||
|
|
||||||
|
final OrderCodec codec = new OrderCodec();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void diagnoses() {
|
||||||
|
assertEquals("not JSON", codec.diagnose(BAD));
|
||||||
|
assertEquals("bad field quantity", codec.diagnose("{\"id\":1,\"quantity\":\"two\"}"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void fallsBackOnBadText() {
|
||||||
|
assertEquals(new Order(0, 0), codec.orDefault(BAD));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void fallsBackOnBadFile(@TempDir Path dir) throws IOException {
|
||||||
|
Path file = Files.writeString(dir.resolve("order.json"), BAD);
|
||||||
|
assertEquals(new Order(0, 0), codec.load(file));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void callerRejectsBadStream() {
|
||||||
|
assertEquals("rejected", new Importer().importOne(BAD));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsBadMap() {
|
||||||
|
assertFalse(codec.isOrder(Map.of("id", "abc")));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
== 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]
|
||||||
|
|
||||||
|
== 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
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
== 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"
|
||||||
|
== 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 ==
|
||||||
|
-- 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
|
||||||
|
== not a JacksonException ==
|
||||||
|
-- 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
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
== 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
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
-- 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]
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
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 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"} ]}"
|
||||||
|
|
||||||
|
== 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
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
===== 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)
|
||||||
|
|
||||||
|
===== 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)
|
||||||
|
at tools.jackson.databind.deser.jdk.NumberDeserializers$IntegerDeserializer.deserialize(NumberDeserializers.java:586)
|
||||||
|
at tools.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:568)
|
||||||
|
at tools.jackson.databind.deser.bean.BeanDeserializer._deserializeWithErrorWrapping(BeanDeserializer.java:1023)
|
||||||
|
at tools.jackson.databind.deser.bean.BeanDeserializer._deserializeUsingPropertyBased(BeanDeserializer.java:833)
|
||||||
|
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.jdk.CollectionDeserializer._deserializeNoNullChecks(CollectionDeserializer.java:585)
|
||||||
|
at tools.jackson.databind.deser.jdk.CollectionDeserializer._deserializeFromArray(CollectionDeserializer.java:394)
|
||||||
|
at tools.jackson.databind.deser.jdk.CollectionDeserializer.deserialize(CollectionDeserializer.java:279)
|
||||||
|
at tools.jackson.databind.deser.jdk.CollectionDeserializer.deserialize(CollectionDeserializer.java:30)
|
||||||
|
at tools.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:568)
|
||||||
|
at tools.jackson.databind.deser.bean.BeanDeserializer._deserializeWithErrorWrapping(BeanDeserializer.java:1023)
|
||||||
|
at tools.jackson.databind.deser.bean.BeanDeserializer._deserializeUsingPropertyBased(BeanDeserializer.java:833)
|
||||||
|
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$1(E06StackTraces.java:17)
|
||||||
|
at com.ankurm.exceptions.E06StackTraces.trace(E06StackTraces.java:25)
|
||||||
|
at com.ankurm.exceptions.E06StackTraces.main(E06StackTraces.java:17)
|
||||||
|
|
||||||
|
===== 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)
|
||||||
|
at tools.jackson.databind.deser.std.StdValueInstantiator.wrapAsDatabindException(StdValueInstantiator.java:581)
|
||||||
|
at tools.jackson.databind.deser.std.StdValueInstantiator.rewrapCtorProblem(StdValueInstantiator.java:602)
|
||||||
|
at tools.jackson.databind.deser.std.StdValueInstantiator.createFromObjectWith(StdValueInstantiator.java:289)
|
||||||
|
at tools.jackson.databind.deser.ValueInstantiator.createFromObjectWith(ValueInstantiator.java:272)
|
||||||
|
at tools.jackson.databind.deser.bean.PropertyBasedCreator.build(PropertyBasedCreator.java:443)
|
||||||
|
at tools.jackson.databind.deser.bean.BeanDeserializer._deserializeUsingPropertyBased(BeanDeserializer.java:938)
|
||||||
|
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$2(E06StackTraces.java:19)
|
||||||
|
at com.ankurm.exceptions.E06StackTraces.trace(E06StackTraces.java:25)
|
||||||
|
at com.ankurm.exceptions.E06StackTraces.main(E06StackTraces.java:19)
|
||||||
|
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)
|
||||||
|
... 12 more
|
||||||
|
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
== 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
|
||||||
|
|
||||||
|
== 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
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
== 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"]
|
||||||
|
|
||||||
|
== 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
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
=== CatchIOException.java ===
|
||||||
|
CatchIOException.java:9: error: exception IOException is never thrown in body of corresponding try statement
|
||||||
|
} catch (IOException e) {
|
||||||
|
^
|
||||||
|
1 error
|
||||||
|
|
||||||
|
=== 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
|
||||||
|
|
||||||
|
=== 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
|
||||||
|
|
||||||
|
=== OldReference.java ===
|
||||||
|
OldReference.java:5: error: cannot find symbol
|
||||||
|
return e.getPath().get(0).getFieldName();
|
||||||
|
^
|
||||||
|
symbol: method getFieldName()
|
||||||
|
location: class Reference
|
||||||
|
1 error
|
||||||
|
|
||||||
|
=== 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
|
||||||
|
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
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]
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
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]
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
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"}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
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"}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
@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
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
thrown : org.springframework.web.client.RestClientException
|
||||||
|
cause : org.springframework.http.converter.HttpMessageNotReadableException
|
||||||
|
cause : tools.jackson.databind.exc.InvalidFormatException
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
[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
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
[WARNING] Changes have been made to pom.xml by:
|
||||||
|
[WARNING] org.openrewrite.java.jackson.UpgradeJackson_2_3_Dependencies
|
||||||
|
[WARNING] org.openrewrite.java.dependencies.ChangeDependency: {oldGroupId=com.fasterxml.jackson.core, oldArtifactId=jackson-databind, newGroupId=tools.jackson.core, newArtifactId=jackson-databind, newVersion=3.1.x}
|
||||||
|
[WARNING] Changes have been made to src/main/java/com/ankurm/orders/OrderCodec.java by:
|
||||||
|
[WARNING] org.openrewrite.java.jackson.IOExceptionToJacksonException
|
||||||
|
[WARNING] org.openrewrite.java.jackson.UseFormatAlignedObjectMappers
|
||||||
|
[WARNING] org.openrewrite.java.jackson.UpgradeJackson_2_3_MethodRenames
|
||||||
|
[WARNING] org.openrewrite.java.ChangeMethodName: {methodPattern=com.fasterxml.jackson.databind.JsonMappingException.Reference getFieldName(), newMethodName=getPropertyName}
|
||||||
|
[WARNING] org.openrewrite.java.jackson.UpgradeJackson_2_3_TypeChanges
|
||||||
|
[WARNING] org.openrewrite.java.ChangeType: {oldFullyQualifiedTypeName=com.fasterxml.jackson.core.JsonParseException, newFullyQualifiedTypeName=tools.jackson.core.exc.StreamReadException}
|
||||||
|
[WARNING] org.openrewrite.java.ChangeType: {oldFullyQualifiedTypeName=com.fasterxml.jackson.core.JsonProcessingException, newFullyQualifiedTypeName=tools.jackson.core.JacksonException}
|
||||||
|
[WARNING] org.openrewrite.java.ChangeType: {oldFullyQualifiedTypeName=com.fasterxml.jackson.databind.JsonMappingException, newFullyQualifiedTypeName=tools.jackson.databind.DatabindException}
|
||||||
|
[WARNING] org.openrewrite.java.jackson.UpgradeJackson_2_3_PackageChanges
|
||||||
|
[WARNING] org.openrewrite.java.ChangePackage: {oldPackageName=com.fasterxml.jackson.databind, newPackageName=tools.jackson.databind, recursive=true}
|
||||||
|
[WARNING] org.openrewrite.java.jackson.RemoveDeadJacksonThrows
|
||||||
|
[WARNING] org.openrewrite.java.RemoveMethodThrows: {methodPattern=*..* *(..), exceptionTypePattern=tools.jackson.core.JacksonException}
|
||||||
|
[INFO] BUILD SUCCESS
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
diff --git a/pom.xml b/pom.xml
|
||||||
|
index 0133bc0..112be2d 100644
|
||||||
|
--- a/pom.xml
|
||||||
|
+++ b/pom.xml
|
||||||
|
@@ -16,9 +16,9 @@
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
- <groupId>com.fasterxml.jackson.core</groupId>
|
||||||
|
+ <groupId>tools.jackson.core</groupId>
|
||||||
|
<artifactId>jackson-databind</artifactId>
|
||||||
|
- <version>2.23.0</version>
|
||||||
|
+ <version>3.1.9</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
diff --git a/src/main/java/com/ankurm/orders/OrderCodec.java b/src/main/java/com/ankurm/orders/OrderCodec.java
|
||||||
|
index f4ed498..cbb2f7c 100644
|
||||||
|
--- a/src/main/java/com/ankurm/orders/OrderCodec.java
|
||||||
|
+++ b/src/main/java/com/ankurm/orders/OrderCodec.java
|
||||||
|
@@ -1,22 +1,23 @@
|
||||||
|
package com.ankurm.orders;
|
||||||
|
|
||||||
|
-import com.fasterxml.jackson.core.JsonParseException;
|
||||||
|
-import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
|
-import com.fasterxml.jackson.databind.JsonMappingException;
|
||||||
|
-import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
+import tools.jackson.databind.ObjectMapper;
|
||||||
|
+import tools.jackson.databind.json.JsonMapper;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Map;
|
||||||
|
+import tools.jackson.core.JacksonException;
|
||||||
|
+import tools.jackson.core.exc.StreamReadException;
|
||||||
|
+import tools.jackson.databind.DatabindException;
|
||||||
|
|
||||||
|
/** Six common ways Jackson 2 code deals with failure. */
|
||||||
|
public class OrderCodec {
|
||||||
|
|
||||||
|
- private final ObjectMapper mapper = new ObjectMapper();
|
||||||
|
+ private final ObjectMapper mapper = new JsonMapper();
|
||||||
|
|
||||||
|
/** 1. declare it */
|
||||||
|
- public Order parse(String json) throws JsonProcessingException {
|
||||||
|
+ public Order parse(String json) {
|
||||||
|
return mapper.readValue(json, Order.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
[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
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
$ 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
|
||||||
|
[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
|
||||||
|
|
||||||
|
$ 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)
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
$ # 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
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
[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
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<!-- Standalone module: build it from inside this directory. Jackson 2 and Jackson 3 are on one
|
||||||
|
classpath on purpose (different packages), so the same failure can be thrown by both. -->
|
||||||
|
<groupId>com.ankurm</groupId>
|
||||||
|
<artifactId>jackson-exceptions</artifactId>
|
||||||
|
<version>1.0.0</version>
|
||||||
|
<name>jackson-exceptions</name>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<maven.compiler.release>25</maven.compiler.release>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<jackson2.version>2.23.0</jackson2.version>
|
||||||
|
<jackson3.version>3.3.0</jackson3.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>tools.jackson.core</groupId>
|
||||||
|
<artifactId>jackson-databind</artifactId>
|
||||||
|
<version>${jackson3.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
|
<artifactId>jackson-databind</artifactId>
|
||||||
|
<version>${jackson2.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</project>
|
||||||
Executable
+15
@@ -0,0 +1,15 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Compiles each file in src/broken/ against Jackson 3 and records javac's own message.
|
||||||
|
# These files are deliberately outside src/main so the Maven build never sees them.
|
||||||
|
set -uo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
CP="target/classes:$(cat target/cp.txt)"
|
||||||
|
OUT=output/09-compile-errors.txt
|
||||||
|
: > "$OUT"
|
||||||
|
for f in src/broken/*.java; do
|
||||||
|
echo "=== $(basename "$f") ===" >> "$OUT"
|
||||||
|
tmp=$(mktemp -d)
|
||||||
|
javac -Xlint:none -d "$tmp" -cp "$CP" "$f" 2>&1 | grep -vE "Picked up|^Note:" | sed "s#^src/broken/##" >> "$OUT"
|
||||||
|
echo >> "$OUT"
|
||||||
|
done
|
||||||
|
echo "wrote $OUT"
|
||||||
Executable
+22
@@ -0,0 +1,22 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# A deliberately small text-substitution migration for exception handling.
|
||||||
|
# Usage: scripts/migrate-regex.sh <project-dir> (edits the files in place: use a copy or a clean branch)
|
||||||
|
# Needs GNU sed. It renames types and packages. It cannot see which catch blocks are now wrong.
|
||||||
|
set -euo pipefail
|
||||||
|
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'
|
||||||
|
# jackson-annotations keeps the old package; the substitutions above never touch com.fasterxml.jackson.annotation.
|
||||||
|
find "$1" -name pom.xml -print0 | xargs -0 sed -i -E \
|
||||||
|
-e 's#<groupId>com\.fasterxml\.jackson\.core</groupId>#<groupId>tools.jackson.core</groupId>#' \
|
||||||
|
-e 's#<version>2\.23\.0</version>#<version>3.3.0</version>#'
|
||||||
Executable
+48
@@ -0,0 +1,48 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Runs both migrations on throwaway copies of migration/before and records the diffs, the build
|
||||||
|
# result and the behaviour tests. Writes output/30..36.
|
||||||
|
set -uo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
MODULE=$PWD
|
||||||
|
MVN="${MVN:-mvn} ${MVN_ARGS:-}"
|
||||||
|
WORK=$(mktemp -d)
|
||||||
|
clean() { grep -vE "Picked up|^WARNING" | sed "s#$WORK#<work>#g; s#$HOME#~#g"; }
|
||||||
|
summary() { # compiler errors or the surefire verdict, without timings
|
||||||
|
clean | grep -E '^\[ERROR\].*\.java|Tests run:|Tests in error|^\[ERROR\] |BUILD' | sed -E 's/, Time elapsed: [0-9.]+ s//; s/ -- Time elapsed.*(<<<.*)/ \1/' | head -30
|
||||||
|
}
|
||||||
|
|
||||||
|
(cd migration/before && $MVN -B test 2>&1 | summary) > output/30-before-jackson2-tests.txt
|
||||||
|
rm -rf migration/before/target
|
||||||
|
|
||||||
|
# --- A: OpenRewrite ---
|
||||||
|
cp -r migration/before "$WORK/rewrite"
|
||||||
|
(cd "$WORK/rewrite" && git init -q && git add -A && git -c user.email=x@x -c user.name=x commit -qm before \
|
||||||
|
&& $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 > "$WORK/rewrite.log" 2>&1)
|
||||||
|
grep -E 'BUILD|Changes have been made| org\.openrewrite' "$WORK/rewrite.log" | clean > output/31-openrewrite-run.txt
|
||||||
|
(cd "$WORK/rewrite" && git diff --no-color -- pom.xml src) > output/32-openrewrite.diff.txt
|
||||||
|
(cd "$WORK/rewrite" && $MVN -B test 2>&1 | summary) > output/33-openrewrite-tests.txt
|
||||||
|
|
||||||
|
# --- B: sed ---
|
||||||
|
cp -r migration/before "$WORK/regex"
|
||||||
|
(cd "$WORK/regex" && git init -q && git add -A && git -c user.email=x@x -c user.name=x commit -qm before)
|
||||||
|
"$MODULE/scripts/migrate-regex.sh" "$WORK/regex"
|
||||||
|
{
|
||||||
|
echo "\$ scripts/migrate-regex.sh <copy>; mvn test"
|
||||||
|
(cd "$WORK/regex" && $MVN -B test 2>&1 | summary)
|
||||||
|
echo
|
||||||
|
echo "\$ scripts/review-catches.sh <copy>"
|
||||||
|
"$MODULE/scripts/review-catches.sh" "$WORK/regex"
|
||||||
|
} > output/34-regex.txt
|
||||||
|
# --- C: sed, then fix only what the compiler points at ---
|
||||||
|
sed -i '/Order orDefault/,/Order load/ s/catch (IOException e)/catch (tools.jackson.core.JacksonException e)/' "$WORK/regex/src/main/java/com/ankurm/orders/OrderCodec.java"
|
||||||
|
{
|
||||||
|
echo "\$ # after fixing the single compile error (orDefault now catches JacksonException)"
|
||||||
|
(cd "$WORK/regex" && $MVN -B test 2>&1 | summary)
|
||||||
|
} > output/35-regex-after-compile-fix.txt
|
||||||
|
|
||||||
|
# --- D: the OpenRewrite result plus the hand fixes ---
|
||||||
|
(cd migration/after && $MVN -B test 2>&1 | summary) > output/36-after-hand-fixes-tests.txt
|
||||||
|
rm -rf migration/after/target
|
||||||
|
echo "work dir kept at $WORK"
|
||||||
Executable
+12
@@ -0,0 +1,12 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Lists the places a rename cannot judge. Every hit needs a human look.
|
||||||
|
# Usage: scripts/review-catches.sh <project-dir>
|
||||||
|
set -uo pipefail
|
||||||
|
cd "$1"
|
||||||
|
files=$(grep -rlE 'tools\.jackson|com\.fasterxml\.jackson\.(core|databind)|OrderCodec' --include='*.java' src | sort)
|
||||||
|
echo "-- catch/throws IOException in files that touch Jackson (or its wrappers)"
|
||||||
|
grep -nE 'catch *\([^)]*(IOException)|throws [^{;]*IOException' $files
|
||||||
|
echo "-- catch IllegalArgumentException (convertValue no longer wraps)"
|
||||||
|
grep -nE 'catch *\([^)]*IllegalArgumentException' $files
|
||||||
|
echo "-- generic catches that now also receive Jackson errors"
|
||||||
|
grep -nE 'catch *\((final )?(RuntimeException|Exception|Throwable) ' $files || echo "(none)"
|
||||||
Executable
+39
@@ -0,0 +1,39 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Regenerates everything in output/. Run from anywhere; needs JDK 25 and Maven.
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
MVN="${MVN:-mvn} ${MVN_ARGS:-}"
|
||||||
|
quiet() { grep -vE "Picked up|^WARNING" || true; }
|
||||||
|
|
||||||
|
build() { # $1 = Jackson 3 version
|
||||||
|
$MVN -B -q clean compile dependency:build-classpath -Dmdep.outputFile=target/cp.txt -Djackson3.version="$1" 2>&1 | quiet
|
||||||
|
CP="target/classes:$(cat target/cp.txt)"
|
||||||
|
}
|
||||||
|
run() { # $1 = output file, $2 = class
|
||||||
|
java -cp "$CP" "com.ankurm.exceptions.$2" 2>&1 | quiet > "output/$1.txt"
|
||||||
|
echo "wrote output/$1.txt"
|
||||||
|
}
|
||||||
|
|
||||||
|
mkdir -p output
|
||||||
|
: > output/10-missing-primitive-by-version.txt
|
||||||
|
for v in 3.1.8 3.2.4; do
|
||||||
|
build "$v"
|
||||||
|
java -cp "$CP" com.ankurm.exceptions.E09MissingPrimitive 2>&1 | quiet >> output/10-missing-primitive-by-version.txt
|
||||||
|
done
|
||||||
|
build 3.3.0
|
||||||
|
java -cp "$CP" com.ankurm.exceptions.E09MissingPrimitive 2>&1 | quiet >> output/10-missing-primitive-by-version.txt
|
||||||
|
|
||||||
|
run 01-hierarchy E01Hierarchy
|
||||||
|
run 02-triggers E02Triggers
|
||||||
|
run 03-silent-catch E03SilentCatch
|
||||||
|
run 04-behaviour-diff E04BehaviourDiff
|
||||||
|
run 05-location-and-path E05Location
|
||||||
|
run 06-stack-traces E06StackTraces
|
||||||
|
run 07-handling E07Handling
|
||||||
|
run 08-custom-and-collect E08CustomAndCollect
|
||||||
|
./scripts/broken.sh
|
||||||
|
|
||||||
|
# Spring Boot tests write output/20..24, the migration script writes output/30..36
|
||||||
|
(cd boot && $MVN -B -q test > /dev/null)
|
||||||
|
echo "wrote output/20..24"
|
||||||
|
./scripts/migrate.sh
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import com.ankurm.exceptions.Order;
|
||||||
|
import java.io.IOException;
|
||||||
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
|
|
||||||
|
class CatchIOException {
|
||||||
|
Order read(JsonMapper mapper, String json) {
|
||||||
|
try {
|
||||||
|
return mapper.readValue(json, Order.class);
|
||||||
|
} catch (IOException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import tools.jackson.core.JacksonException;
|
||||||
|
import tools.jackson.databind.DatabindException;
|
||||||
|
|
||||||
|
class NewException {
|
||||||
|
void fail() {
|
||||||
|
throw new DatabindException("bad data");
|
||||||
|
}
|
||||||
|
|
||||||
|
void failBase() {
|
||||||
|
throw new JacksonException("bad data");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import com.ankurm.exceptions.Order;
|
||||||
|
import tools.jackson.core.JsonProcessingException;
|
||||||
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
|
|
||||||
|
class OldImport {
|
||||||
|
Order read(JsonMapper mapper, String json) throws JsonProcessingException {
|
||||||
|
return mapper.readValue(json, Order.class);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import tools.jackson.databind.DatabindException;
|
||||||
|
|
||||||
|
class OldReference {
|
||||||
|
String field(DatabindException e) {
|
||||||
|
return e.getPath().get(0).getFieldName();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import com.ankurm.exceptions.Order;
|
||||||
|
import tools.jackson.core.JacksonException;
|
||||||
|
import tools.jackson.databind.DatabindException;
|
||||||
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
|
|
||||||
|
class RelatedMultiCatch {
|
||||||
|
Order read(JsonMapper mapper, String json) {
|
||||||
|
try {
|
||||||
|
return mapper.readValue(json, Order.class);
|
||||||
|
} catch (JacksonException | DatabindException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import com.ankurm.exceptions.Order;
|
||||||
|
import tools.jackson.core.JacksonException;
|
||||||
|
import tools.jackson.databind.DatabindException;
|
||||||
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
|
|
||||||
|
class WrongOrder {
|
||||||
|
Order read(JsonMapper mapper, String json) {
|
||||||
|
try {
|
||||||
|
return mapper.readValue(json, Order.class);
|
||||||
|
} catch (JacksonException e) {
|
||||||
|
return null;
|
||||||
|
} catch (DatabindException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package com.ankurm.exceptions;
|
||||||
|
|
||||||
|
import java.net.URISyntaxException;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.jar.JarFile;
|
||||||
|
|
||||||
|
/** Reads the real jars and prints every exception class under JacksonException, Jackson 3 then Jackson 2. */
|
||||||
|
public class E01Hierarchy {
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
System.out.println("== Jackson " + tools.jackson.databind.cfg.PackageVersion.VERSION + " ==");
|
||||||
|
tree(tools.jackson.core.JacksonException.class,
|
||||||
|
find(tools.jackson.core.JacksonException.class, tools.jackson.databind.DatabindException.class));
|
||||||
|
System.out.println();
|
||||||
|
System.out.println("== Jackson " + com.fasterxml.jackson.databind.cfg.PackageVersion.VERSION + " ==");
|
||||||
|
tree(com.fasterxml.jackson.core.JacksonException.class,
|
||||||
|
find(com.fasterxml.jackson.core.JacksonException.class, com.fasterxml.jackson.databind.JsonMappingException.class));
|
||||||
|
System.out.println();
|
||||||
|
System.out.println("Jackson 3 JacksonException superclass chain: " + chain(tools.jackson.core.JacksonException.class));
|
||||||
|
System.out.println("Jackson 2 JacksonException superclass chain: " + chain(com.fasterxml.jackson.core.JacksonException.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
static String chain(Class<?> c) {
|
||||||
|
StringBuilder sb = new StringBuilder(c.getSimpleName());
|
||||||
|
for (Class<?> s = c.getSuperclass(); s != Object.class; s = s.getSuperclass()) sb.append(" -> ").append(s.getSimpleName());
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** All subclasses of root found in the jars that contain the two given classes. */
|
||||||
|
static List<Class<?>> find(Class<?> root, Class<?> databindMarker) throws Exception {
|
||||||
|
List<Class<?>> found = new ArrayList<>();
|
||||||
|
for (Class<?> marker : List.of(root, databindMarker)) {
|
||||||
|
try (JarFile jar = new JarFile(jarOf(marker).toFile())) {
|
||||||
|
for (var entry : jar.stream().toList()) {
|
||||||
|
String n = entry.getName();
|
||||||
|
if (!n.endsWith(".class") || n.startsWith("META-INF") || n.endsWith("-info.class")) continue;
|
||||||
|
String cls = n.substring(0, n.length() - 6).replace('/', '.');
|
||||||
|
Class<?> c = Class.forName(cls, false, E01Hierarchy.class.getClassLoader());
|
||||||
|
if (root.isAssignableFrom(c) && c != root) found.add(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Path jarOf(Class<?> c) throws URISyntaxException {
|
||||||
|
return Path.of(c.getProtectionDomain().getCodeSource().getLocation().toURI());
|
||||||
|
}
|
||||||
|
|
||||||
|
static void tree(Class<?> root, List<Class<?>> all) {
|
||||||
|
System.out.println(root.getName() + " (extends " + root.getSuperclass().getName() + ")");
|
||||||
|
children(root, all, " ");
|
||||||
|
}
|
||||||
|
|
||||||
|
static void children(Class<?> parent, List<Class<?>> all, String indent) {
|
||||||
|
all.stream().filter(c -> c.getSuperclass() == parent)
|
||||||
|
.sorted(Comparator.comparing(Class::getName))
|
||||||
|
.forEach(c -> {
|
||||||
|
String flag = c.isAnnotationPresent(Deprecated.class) ? " @Deprecated" : "";
|
||||||
|
System.out.println(indent + c.getSimpleName() + " [" + c.getPackageName() + "]" + flag);
|
||||||
|
children(c, all, indent + " ");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
package com.ankurm.exceptions;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
import tools.jackson.core.StreamReadFeature;
|
||||||
|
import tools.jackson.databind.DeserializationFeature;
|
||||||
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
|
|
||||||
|
/** One small input per failure, and the exact class Jackson 3 throws for it. */
|
||||||
|
public class E02Triggers {
|
||||||
|
static final JsonMapper MAPPER = JsonMapper.builder().build();
|
||||||
|
|
||||||
|
public interface Shape {}
|
||||||
|
|
||||||
|
@com.fasterxml.jackson.annotation.JsonTypeInfo(use = com.fasterxml.jackson.annotation.JsonTypeInfo.Id.NAME, property = "type")
|
||||||
|
@com.fasterxml.jackson.annotation.JsonSubTypes(@com.fasterxml.jackson.annotation.JsonSubTypes.Type(value = Circle.class, name = "circle"))
|
||||||
|
public interface Figure {}
|
||||||
|
|
||||||
|
public record Circle(int r) implements Figure {}
|
||||||
|
|
||||||
|
public record Positive(int n) {
|
||||||
|
public Positive {
|
||||||
|
if (n <= 0) throw new IllegalArgumentException("n must be positive, got " + n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class Broken {
|
||||||
|
public String getName() { throw new IllegalStateException("lazy collection not initialised"); }
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
System.out.println("== reading: the text is not valid JSON ==");
|
||||||
|
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));
|
||||||
|
show("nesting 1000 deep", () -> MAPPER.readTree("[".repeat(1000) + "]".repeat(1000)));
|
||||||
|
show("duplicate key (strict on)", () -> JsonMapper.builder()
|
||||||
|
.enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()
|
||||||
|
.readTree("{\"id\":1,\"id\":2}"));
|
||||||
|
|
||||||
|
System.out.println("== reading: valid JSON, wrong shape ==");
|
||||||
|
show("string where int expected", () -> MAPPER.readValue("{\"id\":\"abc\"}", Order.class));
|
||||||
|
show("object where array expected", () -> MAPPER.readValue("{\"id\":1,\"quantity\":1,\"lines\":{}}", Order.class));
|
||||||
|
show("null for a primitive", () -> MAPPER.readValue("{\"id\":null,\"quantity\":1}", Order.class));
|
||||||
|
show("primitive left out of a record", () -> MAPPER.readValue("{\"id\":1}", Order.class));
|
||||||
|
show("unknown property (strict on)", () -> JsonMapper.builder()
|
||||||
|
.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).build()
|
||||||
|
.readValue("{\"id\":1,\"quantity\":1,\"colour\":\"red\"}", Order.class));
|
||||||
|
show("trailing token", () -> MAPPER.readValue("{\"id\":1,\"quantity\":1} {}", Order.class));
|
||||||
|
show("empty input", () -> MAPPER.readValue("", Order.class));
|
||||||
|
show("unknown type id", () -> MAPPER.readValue("{\"type\":\"square\"}", Figure.class));
|
||||||
|
show("interface with no type info", () -> MAPPER.readValue("{}", Shape.class));
|
||||||
|
show("record constructor rejects", () -> MAPPER.readValue("{\"n\":-1}", Positive.class));
|
||||||
|
show("tree: asInt() on text", () -> MAPPER.readTree("{\"id\":\"abc\"}").get("id").asInt());
|
||||||
|
|
||||||
|
System.out.println("== writing ==");
|
||||||
|
show("getter throws", () -> MAPPER.writeValueAsString(new Broken()));
|
||||||
|
show("generator misuse", () -> {
|
||||||
|
try (var gen = MAPPER.createGenerator(new java.io.StringWriter())) {
|
||||||
|
gen.writeStartObject();
|
||||||
|
gen.writeString("value without a name");
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
|
||||||
|
System.out.println("== real I/O ==");
|
||||||
|
show("file does not exist", () -> MAPPER.readValue(Path.of("no-such-file.json"), Order.class));
|
||||||
|
show("stream breaks mid-read", () -> MAPPER.readValue(new InputStream() {
|
||||||
|
@Override public int read() throws IOException { throw new IOException("Connection reset"); }
|
||||||
|
}, Order.class));
|
||||||
|
|
||||||
|
System.out.println("== not a JacksonException ==");
|
||||||
|
show("null String", () -> MAPPER.readValue((String) null, Order.class));
|
||||||
|
show("convertValue with bad data", () -> MAPPER.convertValue(Map.of("id", "abc"), Order.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
static void show(String label, Callable<?> call) {
|
||||||
|
System.out.println("-- " + label);
|
||||||
|
try {
|
||||||
|
Object result = call.call();
|
||||||
|
System.out.println(" no exception, result = " + result);
|
||||||
|
} catch (Throwable e) {
|
||||||
|
System.out.println(" " + e.getClass().getName());
|
||||||
|
if (e.getCause() != null) System.out.println(" cause: " + e.getCause().getClass().getName());
|
||||||
|
System.out.println(" " + firstLine(e instanceof tools.jackson.core.JacksonException j ? j.getOriginalMessage() : e.getMessage()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static String firstLine(String s) {
|
||||||
|
if (s == null) return "(no message)";
|
||||||
|
String line = s.lines().findFirst().orElse("");
|
||||||
|
return line.length() > 150 ? line.substring(0, 150) + " ..." : line;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package com.ankurm.exceptions;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The same method written twice. Both compile. Only the Jackson 2 one still handles bad JSON,
|
||||||
|
* because Files.readString keeps "catch (IOException e)" legal in the Jackson 3 one.
|
||||||
|
*/
|
||||||
|
public class E03SilentCatch {
|
||||||
|
static final com.fasterxml.jackson.databind.ObjectMapper J2 = new com.fasterxml.jackson.databind.ObjectMapper();
|
||||||
|
static final tools.jackson.databind.json.JsonMapper J3 = tools.jackson.databind.json.JsonMapper.builder().build();
|
||||||
|
|
||||||
|
static String loadJ2(Path file) {
|
||||||
|
try {
|
||||||
|
Order order = J2.readValue(Files.readString(file), Order.class);
|
||||||
|
return "loaded order " + order.id();
|
||||||
|
} catch (IOException e) { // file errors AND Jackson errors
|
||||||
|
return "fallback: " + e.getClass().getSimpleName();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws IOException {
|
||||||
|
Path bad = Files.createTempFile("order", ".json");
|
||||||
|
Files.writeString(bad, "{\"id\": 1, \"quantity\": }");
|
||||||
|
Path missing = Path.of("no-such-file.json");
|
||||||
|
|
||||||
|
for (Path file : new Path[] {missing, bad}) {
|
||||||
|
System.out.println("== " + (file == bad ? "file with malformed JSON" : "missing file") + " ==");
|
||||||
|
run("Jackson 2, catch (IOException)", () -> loadJ2(file));
|
||||||
|
run("Jackson 3, catch (IOException)", () -> loadJ3(file));
|
||||||
|
run("Jackson 3, catch (IOException | JacksonException)", () -> loadJ3Fixed(file));
|
||||||
|
}
|
||||||
|
Files.delete(bad);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void run(String label, java.util.function.Supplier<String> call) {
|
||||||
|
try {
|
||||||
|
System.out.println(label + "\n " + call.get());
|
||||||
|
} catch (RuntimeException e) {
|
||||||
|
System.out.println(label + "\n ESCAPED: " + e.getClass().getName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package com.ankurm.exceptions;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
|
||||||
|
/** Calls where the thrown type changed in ways an import rename does not express. */
|
||||||
|
public class E04BehaviourDiff {
|
||||||
|
static final com.fasterxml.jackson.databind.ObjectMapper J2 = new com.fasterxml.jackson.databind.ObjectMapper();
|
||||||
|
static final tools.jackson.databind.json.JsonMapper J3 = tools.jackson.databind.json.JsonMapper.builder().build();
|
||||||
|
|
||||||
|
public static class Broken {
|
||||||
|
public String getName() { throw new IllegalStateException("lazy collection not initialised"); }
|
||||||
|
}
|
||||||
|
|
||||||
|
static InputStream resetting() {
|
||||||
|
return new InputStream() {
|
||||||
|
@Override public int read() throws IOException { throw new IOException("Connection reset"); }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Map<String, Object> badMap = Map.of("id", "abc");
|
||||||
|
pair("convertValue(map with bad value)",
|
||||||
|
() -> J2.convertValue(badMap, Order.class),
|
||||||
|
() -> J3.convertValue(badMap, Order.class));
|
||||||
|
pair("readValue(file that does not exist)",
|
||||||
|
() -> J2.readValue(Path.of("no-such-file.json").toFile(), Order.class),
|
||||||
|
() -> J3.readValue(Path.of("no-such-file.json").toFile(), Order.class));
|
||||||
|
pair("readValue(stream that throws IOException)",
|
||||||
|
() -> J2.readValue(resetting(), Order.class),
|
||||||
|
() -> J3.readValue(resetting(), Order.class));
|
||||||
|
pair("writeValueAsString(getter that throws)",
|
||||||
|
() -> J2.writeValueAsString(new Broken()),
|
||||||
|
() -> J3.writeValueAsString(new Broken()));
|
||||||
|
pair("readValue(\"{\\\"id\\\":null}\") into a long",
|
||||||
|
() -> J2.readValue("{\"id\":null,\"quantity\":1}", Order.class),
|
||||||
|
() -> J3.readValue("{\"id\":null,\"quantity\":1}", Order.class));
|
||||||
|
pair("readValue(valid object followed by junk)",
|
||||||
|
() -> J2.readValue("{\"id\":1,\"quantity\":2} oops", Order.class),
|
||||||
|
() -> J3.readValue("{\"id\":1,\"quantity\":2} oops", Order.class));
|
||||||
|
pair("readValue(unknown property)",
|
||||||
|
() -> J2.readValue("{\"id\":1,\"quantity\":2,\"colour\":\"red\"}", Order.class),
|
||||||
|
() -> J3.readValue("{\"id\":1,\"quantity\":2,\"colour\":\"red\"}", Order.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
static void pair(String label, Callable<?> two, Callable<?> three) {
|
||||||
|
System.out.println("-- " + label);
|
||||||
|
System.out.println(" J2: " + describe(two));
|
||||||
|
System.out.println(" J3: " + describe(three));
|
||||||
|
}
|
||||||
|
|
||||||
|
static String describe(Callable<?> call) {
|
||||||
|
try {
|
||||||
|
return "no exception -> " + call.call();
|
||||||
|
} catch (Exception e) {
|
||||||
|
String s = e.getClass().getName();
|
||||||
|
if (e.getCause() != null) s += " (cause: " + e.getCause().getClass().getSimpleName() + ")";
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package com.ankurm.exceptions;
|
||||||
|
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import tools.jackson.core.JacksonException;
|
||||||
|
import tools.jackson.core.StreamReadFeature;
|
||||||
|
import tools.jackson.databind.exc.InvalidFormatException;
|
||||||
|
import tools.jackson.databind.exc.MismatchedInputException;
|
||||||
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
|
|
||||||
|
/** What a JacksonException carries: message, location, path, offending value, target type. */
|
||||||
|
public class E05Location {
|
||||||
|
static final JsonMapper MAPPER = JsonMapper.builder().build();
|
||||||
|
|
||||||
|
static final String BAD = """
|
||||||
|
{"id": 7,
|
||||||
|
"quantity": 2,
|
||||||
|
"lines": [ {"sku": "A-1", "qty": 1},
|
||||||
|
{"sku": "B-2", "qty": "card=4111111111111111"} ]}""";
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
try {
|
||||||
|
MAPPER.readValue(BAD, Order.class);
|
||||||
|
} catch (JacksonException e) {
|
||||||
|
System.out.println("class : " + e.getClass().getSimpleName());
|
||||||
|
System.out.println("getOriginalMessage : " + e.getOriginalMessage());
|
||||||
|
System.out.println("getLocation : line " + e.getLocation().getLineNr() + ", column " + e.getLocation().getColumnNr()
|
||||||
|
+ ", char offset " + e.getLocation().getCharOffset());
|
||||||
|
System.out.println("getPathReference : " + e.getPathReference());
|
||||||
|
System.out.println("field path : " + fieldPath(e));
|
||||||
|
if (e instanceof InvalidFormatException f) System.out.println("getValue : " + f.getValue());
|
||||||
|
if (e instanceof MismatchedInputException m) System.out.println("getTargetType : " + m.getTargetType());
|
||||||
|
System.out.println();
|
||||||
|
System.out.println("getMessage():");
|
||||||
|
System.out.println(e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println();
|
||||||
|
System.out.println("== the same input with StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION enabled ==");
|
||||||
|
try {
|
||||||
|
JsonMapper.builder().enable(StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION).build().readValue(BAD, Order.class);
|
||||||
|
} catch (JacksonException e) {
|
||||||
|
System.out.println(e.getLocation().sourceDescription());
|
||||||
|
}
|
||||||
|
positionInMessage();
|
||||||
|
}
|
||||||
|
|
||||||
|
static void positionInMessage() {
|
||||||
|
String oneLine = "{\"id\": 1, \"quantity\": }";
|
||||||
|
System.out.println();
|
||||||
|
System.out.println("== where the position shows up: same broken text, three ways ==");
|
||||||
|
try {
|
||||||
|
new com.fasterxml.jackson.databind.ObjectMapper().readTree(oneLine);
|
||||||
|
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
|
||||||
|
System.out.println("Jackson 2, String input : " + e.getLocation().offsetDescription());
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
MAPPER.readTree(oneLine);
|
||||||
|
} catch (JacksonException e) {
|
||||||
|
System.out.println("Jackson 3, String input : " + e.getLocation().offsetDescription()
|
||||||
|
+ " but getLineNr()=" + e.getLocation().getLineNr() + ", getColumnNr()=" + e.getLocation().getColumnNr());
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
MAPPER.readTree(oneLine.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||||
|
} catch (JacksonException e) {
|
||||||
|
System.out.println("Jackson 3, byte[] input : " + e.getLocation().offsetDescription()
|
||||||
|
+ " getLineNr()=" + e.getLocation().getLineNr() + ", getColumnNr()=" + e.getLocation().getColumnNr());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "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("^\\.", "");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package com.ankurm.exceptions;
|
||||||
|
|
||||||
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
|
|
||||||
|
/** Prints real stack traces, so you can recognise them in a log. */
|
||||||
|
public class E06StackTraces {
|
||||||
|
static final JsonMapper MAPPER = JsonMapper.builder().build();
|
||||||
|
|
||||||
|
public record Positive(int n) {
|
||||||
|
public Positive {
|
||||||
|
if (n <= 0) throw new IllegalArgumentException("n must be positive, got " + n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
trace("malformed JSON", () -> MAPPER.readValue("{\"id\": 1, \"quantity\": }", Order.class));
|
||||||
|
trace("wrong type inside a list", () -> MAPPER.readValue(
|
||||||
|
"{\"id\":1,\"quantity\":1,\"lines\":[{\"sku\":\"A\",\"qty\":\"two\"}]}", Order.class));
|
||||||
|
trace("record constructor rejects the value", () -> MAPPER.readValue("{\"n\":-1}", Positive.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
static void trace(String title, Runnable r) {
|
||||||
|
System.out.println("===== " + title + " =====");
|
||||||
|
try {
|
||||||
|
r.run();
|
||||||
|
} catch (RuntimeException e) {
|
||||||
|
e.printStackTrace(System.out);
|
||||||
|
}
|
||||||
|
System.out.println();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package com.ankurm.exceptions;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.CompletionException;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
import tools.jackson.core.JacksonException;
|
||||||
|
import tools.jackson.core.exc.JacksonIOException;
|
||||||
|
import tools.jackson.core.exc.StreamConstraintsException;
|
||||||
|
import tools.jackson.core.exc.StreamReadException;
|
||||||
|
import tools.jackson.databind.DatabindException;
|
||||||
|
import tools.jackson.databind.exc.InvalidDefinitionException;
|
||||||
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
|
|
||||||
|
/** Catching versus propagating: who is at fault, and what unchecked changes about lambdas and futures. */
|
||||||
|
public class E07Handling {
|
||||||
|
static final JsonMapper MAPPER = JsonMapper.builder().build();
|
||||||
|
|
||||||
|
public interface Shape {}
|
||||||
|
|
||||||
|
enum Fault { BAD_INPUT, TRANSPORT, OUR_BUG }
|
||||||
|
|
||||||
|
/** 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
System.out.println("== who is at fault ==");
|
||||||
|
classifyOne("syntax error", () -> MAPPER.readValue("{", Order.class));
|
||||||
|
classifyOne("wrong type", () -> MAPPER.readValue("{\"id\":\"x\"}", Order.class));
|
||||||
|
classifyOne("too deep", () -> MAPPER.readTree("[".repeat(1000)));
|
||||||
|
classifyOne("no way to construct type", () -> MAPPER.readValue("{}", Shape.class));
|
||||||
|
classifyOne("connection reset", () -> MAPPER.readValue(new InputStream() {
|
||||||
|
@Override public int read() throws IOException { throw new IOException("Connection reset"); }
|
||||||
|
}, Order.class));
|
||||||
|
|
||||||
|
System.out.println();
|
||||||
|
System.out.println("== a catch that misses StreamConstraintsException ==");
|
||||||
|
try {
|
||||||
|
try {
|
||||||
|
MAPPER.readTree("[".repeat(1000));
|
||||||
|
} catch (StreamReadException | DatabindException e) {
|
||||||
|
System.out.println("handled as bad input");
|
||||||
|
}
|
||||||
|
} catch (JacksonException e) {
|
||||||
|
System.out.println("slipped past catch (StreamReadException | DatabindException): " + e.getClass().getSimpleName());
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println();
|
||||||
|
System.out.println("== streams: no try/catch needed, one bad element ends the pipeline ==");
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
System.out.println("skip-and-report instead:");
|
||||||
|
docs.stream().flatMap(d -> {
|
||||||
|
try {
|
||||||
|
return Stream.of(MAPPER.readValue(d, Order.class));
|
||||||
|
} catch (JacksonException e) {
|
||||||
|
System.out.println(" skipped " + d + " (" + e.getClass().getSimpleName() + ")");
|
||||||
|
return Stream.empty();
|
||||||
|
}
|
||||||
|
}).forEach(o -> System.out.println(" parsed " + o.id()));
|
||||||
|
|
||||||
|
System.out.println();
|
||||||
|
System.out.println("== CompletableFuture wraps it ==");
|
||||||
|
try {
|
||||||
|
CompletableFuture.supplyAsync(() -> MAPPER.readValue("{", Order.class)).join();
|
||||||
|
} catch (JacksonException e) {
|
||||||
|
System.out.println("caught JacksonException");
|
||||||
|
} catch (CompletionException e) {
|
||||||
|
System.out.println("join() threw CompletionException, cause " + e.getCause().getClass().getSimpleName());
|
||||||
|
}
|
||||||
|
System.out.println("exceptionally(): "
|
||||||
|
+ CompletableFuture.supplyAsync(() -> "ok " + MAPPER.readValue("{", Order.class).id())
|
||||||
|
.exceptionally(t -> "sees " + t.getClass().getSimpleName() + " wrapping " + t.getCause().getClass().getSimpleName())
|
||||||
|
.join());
|
||||||
|
|
||||||
|
System.out.println();
|
||||||
|
System.out.println("== an old catch (RuntimeException) now swallows Jackson errors ==");
|
||||||
|
try {
|
||||||
|
MAPPER.readValue("{", Order.class);
|
||||||
|
} catch (RuntimeException e) {
|
||||||
|
System.out.println("generic handler got " + e.getClass().getSimpleName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void classifyOne(String label, Runnable r) {
|
||||||
|
try {
|
||||||
|
r.run();
|
||||||
|
} catch (JacksonException e) {
|
||||||
|
System.out.printf("%-26s %-28s %s%n", label, e.getClass().getSimpleName(), classify(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package com.ankurm.exceptions;
|
||||||
|
|
||||||
|
import tools.jackson.core.JacksonException;
|
||||||
|
import tools.jackson.core.JsonParser;
|
||||||
|
import tools.jackson.databind.DatabindException;
|
||||||
|
import tools.jackson.databind.DeserializationContext;
|
||||||
|
import tools.jackson.databind.ValueDeserializer;
|
||||||
|
import tools.jackson.databind.annotation.JsonDeserialize;
|
||||||
|
import tools.jackson.databind.exc.CollectedProblem;
|
||||||
|
import tools.jackson.databind.exc.DeferredBindingException;
|
||||||
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
|
|
||||||
|
/** Throwing from your own deserializer, and collecting several binding problems in one pass. */
|
||||||
|
public class E08CustomAndCollect {
|
||||||
|
static final JsonMapper MAPPER = JsonMapper.builder().build();
|
||||||
|
|
||||||
|
/** 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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public record A(@JsonDeserialize(using = Plain.class) Integer qty) {}
|
||||||
|
|
||||||
|
public record B(@JsonDeserialize(using = Reported.class) Integer qty) {}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
System.out.println("== exception thrown inside a custom deserializer ==");
|
||||||
|
for (Class<?> type : new Class<?>[] {A.class, B.class}) {
|
||||||
|
try {
|
||||||
|
MAPPER.readValue("{\"qty\":\"two\"}", type);
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.out.println((type == A.class ? "parseInt left alone : " : "reported via context: ") + e.getClass().getName());
|
||||||
|
if (e instanceof JacksonException j) System.out.println(" path " + j.getPathReference());
|
||||||
|
if (e.getCause() != null) System.out.println(" cause " + e.getCause().getClass().getName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println();
|
||||||
|
System.out.println("== collect several problems (ObjectReader.problemCollectingReader) ==");
|
||||||
|
String bad = "{\"id\":\"x\",\"quantity\":\"y\",\"lines\":[{\"sku\":\"A\",\"qty\":\"z\"}]}";
|
||||||
|
try {
|
||||||
|
MAPPER.readerFor(Order.class).readValue(bad);
|
||||||
|
} catch (DatabindException e) {
|
||||||
|
System.out.println("plain readValue stops at the first: " + e.getPathReference());
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.ankurm.exceptions;
|
||||||
|
|
||||||
|
import tools.jackson.core.JacksonException;
|
||||||
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
|
|
||||||
|
/** Run on more than one 3.x line: whether a missing primitive record component throws has changed. */
|
||||||
|
public class E09MissingPrimitive {
|
||||||
|
public record Stock(String sku, int count) {}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
JsonMapper mapper = JsonMapper.builder().build();
|
||||||
|
System.out.println("jackson-databind " + tools.jackson.databind.cfg.PackageVersion.VERSION);
|
||||||
|
for (String json : new String[] {"{\"sku\":\"A\",\"count\":null}", "{\"sku\":\"A\"}"}) {
|
||||||
|
try {
|
||||||
|
System.out.println(" " + json + " -> " + mapper.readValue(json, Stock.class));
|
||||||
|
} catch (JacksonException e) {
|
||||||
|
System.out.println(" " + json + " -> " + e.getClass().getSimpleName() + ": " + e.getOriginalMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.ankurm.exceptions;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** The one data shape every example reads. */
|
||||||
|
public record Order(long id, int quantity, List<Line> lines) {
|
||||||
|
public record Line(String sku, int qty) {}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user