diff --git a/src/main/java/io/github/nstdio/http/ext/BodySubscribers.java b/src/main/java/io/github/nstdio/http/ext/BodySubscribers.java index 37419d1..7dc65a1 100644 --- a/src/main/java/io/github/nstdio/http/ext/BodySubscribers.java +++ b/src/main/java/io/github/nstdio/http/ext/BodySubscribers.java @@ -16,7 +16,8 @@ package io.github.nstdio.http.ext; -import static java.net.http.HttpResponse.BodySubscribers.ofInputStream; +import static java.net.http.HttpResponse.BodySubscribers.mapping; +import static java.net.http.HttpResponse.BodySubscribers.ofByteArray; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JavaType; @@ -55,9 +56,9 @@ private static BodySubscriber ofJson(JavaType targetType) { } private static BodySubscriber ofJson(ObjectMapper objectMapper, JavaType targetType) { - return new AsyncMappingSubscriber<>(ofInputStream(), is -> { - try (var stream = is) { - return objectMapper.readValue(stream, targetType); + return mapping(ofByteArray(), bytes -> { + try { + return objectMapper.readValue(bytes, targetType); } catch (IOException e) { throw new UncheckedIOException(e); } diff --git a/src/test/java/io/github/nstdio/http/ext/BodyHandlersTest.java b/src/test/java/io/github/nstdio/http/ext/BodyHandlersTest.java index f6fdaea..b8e22d3 100644 --- a/src/test/java/io/github/nstdio/http/ext/BodyHandlersTest.java +++ b/src/test/java/io/github/nstdio/http/ext/BodyHandlersTest.java @@ -17,7 +17,9 @@ package io.github.nstdio.http.ext; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIOException; +import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; @@ -53,5 +55,16 @@ void shouldProperlyReadJson() { assertThat(body1).isNotEmpty(); assertThat(body2).isNotNull(); } + + @Test + void shouldThrowUncheckedExceptionIfCannotRead() { + //given + var request = HttpRequest.newBuilder(URI.create("https://httpbin.org/html")).build(); + + //when + assertThatIOException() + .isThrownBy(() -> client.send(request, BodyHandlers.ofJson(Object.class))) + .withRootCauseExactlyInstanceOf(JsonParseException.class); + } } } \ No newline at end of file