11package org .togetherjava .tjbot .features .utils ;
22
3+ import com .fasterxml .jackson .annotation .JsonIgnoreProperties ;
34import com .fasterxml .jackson .databind .ObjectMapper ;
5+ import org .slf4j .Logger ;
6+ import org .slf4j .LoggerFactory ;
47
58import java .io .IOException ;
69import java .io .UncheckedIOException ;
1215 * Handle the parsing of json in a http request.
1316 */
1417public 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