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:
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user