Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 31 additions & 4 deletions src/main/java/rest/koios/client/backend/api/base/BaseService.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@
@Getter
public class BaseService {

private static final ObjectMapper ERROR_MAPPER = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

private final Retrofit retrofit;
private int retriesCount = 5;
private boolean retryOnTimeout = true;
Expand Down Expand Up @@ -141,13 +144,35 @@ protected <T> Result<T> processResponseGetOne(Call<List<T>> call) throws ApiExce
return (Result<T>) Result.builder().successful(false).response("Response Body is Invalid").code(500).build();
}
} else {
return (Result<T>) Result.builder().successful(false).response(Objects.requireNonNull(response.errorBody()).string()).code(response.code()).build();
String errorBody = Objects.requireNonNull(response.errorBody()).string();
return (Result<T>) Result.builder().successful(false).response(errorBody).code(response.code()).error(parseError(errorBody)).build();
}
} catch (IOException e) {
throw new ApiException(e.getMessage(), e);
}
}

/**
* Parses a JSON error body returned by Koios into a {@link KoiosError}.
*
* @param body raw response body, which may be plain text rather than JSON
* @return parsed error, or null if the body is blank, is not JSON, or carries none of the
* expected fields
*/
private static KoiosError parseError(String body) {
if (body == null || body.trim().isEmpty()) {
return null;
}
try {
KoiosError error = ERROR_MAPPER.readValue(body, KoiosError.class);
boolean empty = error.getCode() == null && error.getMessage() == null
&& error.getDetails() == null && error.getHint() == null;
return empty ? null : error;
} catch (IOException e) {
return null;
}
}

protected <T> Result<T> badRequestResult(String responseText) {
return (Result<T>) Result.builder().successful(false).response(responseText).code(400).build();
}
Expand All @@ -163,10 +188,12 @@ protected <T> Result<T> badRequestResult(String responseText) {
protected <T> Result<T> processResponse(Call<?> call) throws ApiException {
try {
Response<T> response = (Response<T>) execute(call);
if (response.isSuccessful())
if (response.isSuccessful()) {
return (Result<T>) Result.builder().successful(true).response(response.toString()).value(response.body()).code(response.code()).build();
else
return (Result<T>) Result.builder().successful(false).response(Objects.requireNonNull(response.errorBody()).string()).code(response.code()).build();
} else {
String errorBody = Objects.requireNonNull(response.errorBody()).string();
return (Result<T>) Result.builder().successful(false).response(errorBody).code(response.code()).error(parseError(errorBody)).build();
}
} catch (IOException e) {
throw new ApiException(e.getMessage(), e);
}
Expand Down
46 changes: 46 additions & 0 deletions src/main/java/rest/koios/client/backend/api/base/KoiosError.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package rest.koios.client.backend.api.base;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;

/**
* Structured error returned by a Koios instance.
* <p>
* Koios is served by PostgREST, which reports failures as a JSON object rather than plain text:
* <pre>
* {"code":"42703","details":null,"hint":null,"message":"column pgrst_call.ticker does not exist"}
* </pre>
* When a failing response carries such a body it is parsed into this object and exposed as the
* {@code error} field of {@link Result}. Responses whose body is not JSON of this shape leave it
* null; the raw body is always available from the {@code response} field either way.
*/
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@JsonIgnoreProperties(ignoreUnknown = true)
public class KoiosError {

/**
* Error code as reported by the server, e.g. a PostgreSQL SQLSTATE such as "42703"
* (null if not applicable)
*/
private String code;

/**
* Human readable description of the failure (null if not applicable)
*/
private String message;

/**
* Additional detail about the failure (null if not applicable)
*/
private String details;

/**
* Suggested way to resolve the failure (null if not applicable)
*/
private String hint;
}
6 changes: 6 additions & 0 deletions src/main/java/rest/koios/client/backend/api/base/Result.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,11 @@ public class Result<T> {
String response;
int code;
T value;

/**
* Structured error, when the failing response carried a JSON error body.
* Null on success, and null when the body was not JSON of that shape.
*/
KoiosError error;
}

Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,35 @@ void successfulResponseIsReturnedTest() throws ApiException {
Assertions.assertEquals("Conway", result.getValue().getEra());
}

@Test
void successCarriesNoErrorTest() throws ApiException {
server.enqueue(new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "application/json")
.setBody("[{\"hash\":\"abc\",\"epoch_no\":655,\"era\":\"Conway\"}]"));

Result<Tip> result = backendService.getNetworkService().getChainTip();

Assertions.assertTrue(result.isSuccessful());
Assertions.assertNull(result.getError());
}

@Test
void partialErrorBodyIsParsedTest() throws ApiException {
server.enqueue(new MockResponse()
.setResponseCode(400)
.setHeader("Content-Type", "application/json")
.setBody("{\"message\":\"request body too large\",\"hint\":\"send fewer ids\"}"));

Result<Tip> result = backendService.getNetworkService().getChainTip();

KoiosError error = result.getError();
Assertions.assertNotNull(error);
Assertions.assertEquals("request body too large", error.getMessage());
Assertions.assertEquals("send fewer ids", error.getHint());
Assertions.assertNull(error.getCode());
}

@Test
void serverErrorBodyIsSurfacedTest() throws ApiException {
String postgrestError = "{\"code\":\"42703\",\"details\":null,\"hint\":null," +
Expand All @@ -64,6 +93,13 @@ void serverErrorBodyIsSurfacedTest() throws ApiException {
Assertions.assertEquals(400, result.getCode());
Assertions.assertEquals(postgrestError, result.getResponse());
Assertions.assertNull(result.getValue());
// the same body, parsed
KoiosError error = result.getError();
Assertions.assertNotNull(error);
Assertions.assertEquals("42703", error.getCode());
Assertions.assertEquals("column pgrst_call.ticker does not exist", error.getMessage());
Assertions.assertNull(error.getDetails());
Assertions.assertNull(error.getHint());
}

@Test
Expand All @@ -75,6 +111,8 @@ void internalServerErrorIsSurfacedTest() throws ApiException {
Assertions.assertFalse(result.isSuccessful());
Assertions.assertEquals(500, result.getCode());
Assertions.assertEquals("upstream failure", result.getResponse());
// a plain-text body is not a structured error; the raw text is still available
Assertions.assertNull(result.getError());
}

@Test
Expand Down
Loading