Skip to content

Commit 9ff5cb8

Browse files
authored
[Feature/JShell] Improve error messages (#1115)
[feature/JShell] Improve error messages
1 parent d3a19aa commit 9ff5cb8

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

application/src/main/java/org/togetherjava/tjbot/features/utils/ResponseUtils.java

+18-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package org.togetherjava.tjbot.features.utils;
22

3+
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
34
import com.fasterxml.jackson.databind.ObjectMapper;
5+
import org.slf4j.Logger;
6+
import org.slf4j.LoggerFactory;
47

58
import java.io.IOException;
69
import java.io.UncheckedIOException;
@@ -12,6 +15,8 @@
1215
* Handle the parsing of json in a http request.
1316
*/
1417
public class ResponseUtils {
18+
private static final Logger logger = LoggerFactory.getLogger(ResponseUtils.class);
19+
1520
private ResponseUtils() {}
1621

1722
/**
@@ -29,9 +34,12 @@ public static <T> BodyHandler<T> ofJson(Class<T> type, ObjectMapper mapper) {
2934
if (responseInfo.statusCode() == 200 || responseInfo.statusCode() == 204) {
3035
return uncheckedParseJson(type, mapper, bytes);
3136
}
32-
String errorMessage = tryParseError(bytes, mapper)
33-
.orElse("Request failed with status: " + responseInfo.statusCode());
34-
throw new UncheckedRequestFailedException(errorMessage, responseInfo.statusCode());
37+
ErrorAndMessage errorMessage =
38+
tryParseError(bytes, mapper).orElse(new ErrorAndMessage("Bad Request",
39+
"Request failed with status: " + responseInfo.statusCode()));
40+
throw new UncheckedRequestFailedException(
41+
errorMessage.error() + ". " + errorMessage.message(),
42+
responseInfo.statusCode());
3543
});
3644
}
3745

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

46-
private static Optional<String> tryParseError(byte[] bytes, ObjectMapper mapper) {
54+
@JsonIgnoreProperties(ignoreUnknown = true)
55+
private record ErrorAndMessage(String error, String message) {
56+
}
57+
58+
private static Optional<ErrorAndMessage> tryParseError(byte[] bytes, ObjectMapper mapper) {
4759
try {
48-
return Optional.ofNullable(mapper.readTree(bytes).get("error").asText());
60+
return Optional.ofNullable(mapper.readValue(bytes, ErrorAndMessage.class));
4961
} catch (Exception e) {
62+
logger.error("Error parsing json", e);
5063
return Optional.empty();
5164
}
5265
}

0 commit comments

Comments
 (0)