1
1
package org .togetherjava .tjbot .features .utils ;
2
2
3
+ import com .fasterxml .jackson .annotation .JsonIgnoreProperties ;
3
4
import com .fasterxml .jackson .databind .ObjectMapper ;
5
+ import org .slf4j .Logger ;
6
+ import org .slf4j .LoggerFactory ;
4
7
5
8
import java .io .IOException ;
6
9
import java .io .UncheckedIOException ;
12
15
* Handle the parsing of json in a http request.
13
16
*/
14
17
public class ResponseUtils {
18
+ private static final Logger logger = LoggerFactory .getLogger (ResponseUtils .class );
19
+
15
20
private ResponseUtils () {}
16
21
17
22
/**
@@ -29,9 +34,12 @@ public static <T> BodyHandler<T> ofJson(Class<T> type, ObjectMapper mapper) {
29
34
if (responseInfo .statusCode () == 200 || responseInfo .statusCode () == 204 ) {
30
35
return uncheckedParseJson (type , mapper , bytes );
31
36
}
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 ());
35
43
});
36
44
}
37
45
@@ -43,10 +51,15 @@ private static <T> T uncheckedParseJson(Class<T> type, ObjectMapper mapper, byte
43
51
}
44
52
}
45
53
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 ) {
47
59
try {
48
- return Optional .ofNullable (mapper .readTree (bytes ). get ( "error" ). asText ( ));
60
+ return Optional .ofNullable (mapper .readValue (bytes , ErrorAndMessage . class ));
49
61
} catch (Exception e ) {
62
+ logger .error ("Error parsing json" , e );
50
63
return Optional .empty ();
51
64
}
52
65
}
0 commit comments