Skip to content

Commit

Permalink
Merge pull request #276 from avaje/feature/HttpException-response-body
Browse files Browse the repository at this point in the history
[http client] HttpException internally read the response body once
  • Loading branch information
rbygrave authored Aug 24, 2023
2 parents 6179f7e + 8a3ad03 commit 63f88be
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
17 changes: 11 additions & 6 deletions http-client/src/main/java/io/avaje/http/client/HttpException.java
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
*
Expand All @@ -106,8 +114,7 @@ public <T> T bean(Class<T> cls) {
if (httpResponse == null) {
return null;
}
final BodyContent body = context.readErrorContent(responseAsBytes, httpResponse);
return context.readBean(cls, body);
return context.readBean(cls, readBody());
}

/**
Expand All @@ -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);
}

/**
Expand All @@ -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();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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");
}
}

Expand Down

0 comments on commit 63f88be

Please sign in to comment.