From 80f2d519348cd3312f8c78557c8623440266b5b0 Mon Sep 17 00:00:00 2001 From: Cyborger1 <45152844+Cyborger1@users.noreply.github.com> Date: Wed, 9 Nov 2022 10:57:55 -0500 Subject: [PATCH] Better logging for unparsable error messages (#168) --- .../botdetector/http/BotDetectorClient.java | 38 +++++++++++-------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/src/main/java/com/botdetector/http/BotDetectorClient.java b/src/main/java/com/botdetector/http/BotDetectorClient.java index ec7a6865..ca598cb1 100644 --- a/src/main/java/com/botdetector/http/BotDetectorClient.java +++ b/src/main/java/com/botdetector/http/BotDetectorClient.java @@ -553,29 +553,35 @@ private T processResponse(Gson gson, Response response, Type type) throws IO private IOException getIOException(Response response) { int code = response.code(); - if (code == 422) - { - // TODO: Parse actual error info received from FastAPI (details -> loc, msg, ctx, etc.) - return new ValidationException("Error 422 from API, invalid data format"); - } - else if (code >= 400 && code < 500) + if (code >= 400 && code < 500) { try { - Map map = gson.fromJson(response.body().string(), - new TypeToken>() - { - }.getType()); + String body = response.body().string(); + try + { + Map map = gson.fromJson(body, + new TypeToken>() + { + }.getType()); - // "error" has priority if it exists, else use "detail" (FastAPI) - String error = map.get("error"); - if (Strings.isNullOrEmpty(error)) + // "error" has priority if it exists, else use "detail" (FastAPI) + String error = map.get("error"); + if (Strings.isNullOrEmpty(error)) + { + error = map.getOrDefault("detail", "Unknown " + code + " error from API"); + } + return new IOException(error); + } + catch (JsonSyntaxException ex) { - error = map.getOrDefault("detail", "Unknown " + code + " error from API"); + // If can't parse, just log the response body + // TODO: Parse actual error info received from FastAPI (details -> loc, msg, ctx, etc.) especially for 422 errors + log.warn("Received HTTP error code " + code + " from API with the following response body:\n" + body); + return new IOException("Error " + code + ", see log for more info"); } - return new IOException(error); } - catch (IOException | JsonSyntaxException ex) + catch (IOException ex) { return new IOException("Error " + code + " with no error info", ex); }