Skip to content

Commit

Permalink
[Feature/JShell] Improve error messages (#1115)
Browse files Browse the repository at this point in the history
[feature/JShell] Improve error messages
  • Loading branch information
Alathreon authored May 15, 2024
1 parent d3a19aa commit 9ff5cb8
Showing 1 changed file with 18 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package org.togetherjava.tjbot.features.utils;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UncheckedIOException;
Expand All @@ -12,6 +15,8 @@
* Handle the parsing of json in a http request.
*/
public class ResponseUtils {
private static final Logger logger = LoggerFactory.getLogger(ResponseUtils.class);

private ResponseUtils() {}

/**
Expand All @@ -29,9 +34,12 @@ public static <T> BodyHandler<T> ofJson(Class<T> type, ObjectMapper mapper) {
if (responseInfo.statusCode() == 200 || responseInfo.statusCode() == 204) {
return uncheckedParseJson(type, mapper, bytes);
}
String errorMessage = tryParseError(bytes, mapper)
.orElse("Request failed with status: " + responseInfo.statusCode());
throw new UncheckedRequestFailedException(errorMessage, responseInfo.statusCode());
ErrorAndMessage errorMessage =
tryParseError(bytes, mapper).orElse(new ErrorAndMessage("Bad Request",
"Request failed with status: " + responseInfo.statusCode()));
throw new UncheckedRequestFailedException(
errorMessage.error() + ". " + errorMessage.message(),
responseInfo.statusCode());
});
}

Expand All @@ -43,10 +51,15 @@ private static <T> T uncheckedParseJson(Class<T> type, ObjectMapper mapper, byte
}
}

private static Optional<String> tryParseError(byte[] bytes, ObjectMapper mapper) {
@JsonIgnoreProperties(ignoreUnknown = true)
private record ErrorAndMessage(String error, String message) {
}

private static Optional<ErrorAndMessage> tryParseError(byte[] bytes, ObjectMapper mapper) {
try {
return Optional.ofNullable(mapper.readTree(bytes).get("error").asText());
return Optional.ofNullable(mapper.readValue(bytes, ErrorAndMessage.class));
} catch (Exception e) {
logger.error("Error parsing json", e);
return Optional.empty();
}
}
Expand Down

0 comments on commit 9ff5cb8

Please sign in to comment.