Skip to content

Commit

Permalink
Small refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
StefanBratanov committed Feb 9, 2024
1 parent de5c957 commit 900a8e6
Showing 1 changed file with 31 additions and 20 deletions.
51 changes: 31 additions & 20 deletions src/main/java/io/github/stefanbratanov/jvm/openai/OpenAIClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -134,28 +134,39 @@ private String[] getAuthenticationHeaders(String apiKey, Optional<String> organi
}

private Optional<OpenAIException.Error> getErrorFromHttpResponse(HttpResponse<?> httpResponse) {
try {
byte[] body;
if (httpResponse.body() instanceof byte[]) {
body = (byte[]) httpResponse.body();
} else if (httpResponse.body() instanceof Path path) {
body = Files.readAllBytes(path);
} else if (httpResponse.body() instanceof Stream<?> stream) {
body = stream.map(String.class::cast).collect(Collectors.joining()).getBytes();
} else {
return Optional.empty();
}
return getErrorBodyFromHttpResponse(httpResponse)
.flatMap(
body -> {
try {
JsonNode errorNode = objectMapper.readTree(body).get("error");
if (errorNode == null) {
return Optional.empty();
}
return Optional.of(
objectMapper.treeToValue(errorNode, OpenAIException.Error.class));
} catch (JsonProcessingException ex) {
return Optional.empty();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
});
}

private Optional<byte[]> getErrorBodyFromHttpResponse(HttpResponse<?> httpResponse) {
byte[] body;
if (httpResponse.body() instanceof byte[]) {
body = (byte[]) httpResponse.body();
} else if (httpResponse.body() instanceof Path path) {
try {
JsonNode errorNode = objectMapper.readTree(body).get("error");
if (errorNode == null) {
return Optional.empty();
}
return Optional.of(objectMapper.treeToValue(errorNode, OpenAIException.Error.class));
} catch (JsonProcessingException ex) {
return Optional.empty();
body = Files.readAllBytes(path);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
} catch (IOException ex) {
throw new UncheckedIOException(ex);
} else if (httpResponse.body() instanceof Stream<?> stream) {
body = stream.map(String.class::cast).collect(Collectors.joining()).getBytes();
} else {
return Optional.empty();
}
return Optional.of(body);
}
}

0 comments on commit 900a8e6

Please sign in to comment.