diff --git a/http-client/src/main/java/io/avaje/http/client/HttpException.java b/http-client/src/main/java/io/avaje/http/client/HttpException.java index c9dce999..36024758 100644 --- a/http-client/src/main/java/io/avaje/http/client/HttpException.java +++ b/http-client/src/main/java/io/avaje/http/client/HttpException.java @@ -46,6 +46,7 @@ public class HttpException extends RuntimeException { private final boolean responseAsBytes; private final DHttpClientContext context; private final HttpResponse httpResponse; + private BodyContent body; /** * Create with status code and message. @@ -96,6 +97,13 @@ public HttpException(int statusCode, Throwable cause) { this.responseAsBytes = true; } + private BodyContent readBody() { + if (body == null) { + body = context.readErrorContent(responseAsBytes, httpResponse); + } + return body; + } + /** * Return the response body content as a bean, or else null if body content doesn't exist. * @@ -106,8 +114,7 @@ public T bean(Class cls) { if (httpResponse == null) { return null; } - final BodyContent body = context.readErrorContent(responseAsBytes, httpResponse); - return context.readBean(cls, body); + return context.readBean(cls, readBody()); } /** @@ -117,8 +124,7 @@ public String bodyAsString() { if (httpResponse == null) { return null; } - final BodyContent body = context.readErrorContent(responseAsBytes, httpResponse); - return new String(body.content(), StandardCharsets.UTF_8); + return new String(readBody().content(), StandardCharsets.UTF_8); } /** @@ -128,8 +134,7 @@ public byte[] bodyAsBytes() { if (httpResponse == null) { return null; } - final BodyContent body = context.readErrorContent(responseAsBytes, httpResponse); - return body.content(); + return readBody().content(); } /** diff --git a/http-client/src/test/java/io/avaje/http/client/HelloControllerTest.java b/http-client/src/test/java/io/avaje/http/client/HelloControllerTest.java index 7be55f2e..c90bdc56 100644 --- a/http-client/src/test/java/io/avaje/http/client/HelloControllerTest.java +++ b/http-client/src/test/java/io/avaje/http/client/HelloControllerTest.java @@ -517,6 +517,9 @@ void asPlainString_throwingHttpException() { // convert json error response body to a bean final ErrorResponse errorResponse = httpException.bean(ErrorResponse.class); assertThat(errorResponse.get("email")).isEqualTo("must be a well-formed email address"); + + String responseBodyString = httpException.bodyAsString(); + assertThat(responseBodyString).startsWith("{\"message\":\"Request failed validation\",\"errors\":"); } @Test @@ -1249,6 +1252,7 @@ void postForm_asBytes_validation_expect_badRequest_extractError() { final byte[] rawBytes = e.bodyAsBytes(); assertThat(rawBytes).isNotNull(); + assertThat(new String(rawBytes, 0, rawBytes.length, StandardCharsets.UTF_8)).contains("must be a valid URL"); } }