private ApiException handleError(Response response, ResponseBody body) throws IOException { String in = body.string(); if (!Objects.equals(response.header("Content-Type"), "application/json")) { return new ApiException("Unexpected content-type " + response.header("Content-Type"), response.request(), response, in); } BuycraftError error = gson.fromJson(in, BuycraftError.class); if (error != null) { return new ApiException(error.getErrorMessage(), response.request(), response, in); } else { return new ApiException("Unknown error occurred whilst deserializing error object.", response.request(), response, in); } }
private <T> T get(String endpoint, CacheControl control, Type type) throws IOException, ApiException { try { Request.Builder requestBuilder = getBuilder(endpoint).get(); if (control != null) requestBuilder.cacheControl(control); Request request = requestBuilder.build(); Response response = httpClient.newCall(request).execute(); try (ResponseBody body = response.body()) { if (response.isSuccessful()) { try { return gson.fromJson(body.charStream(), type); } catch (JsonSyntaxException e) { throw new ApiException("Unable to parse response.", response.request(), response, body.string()); } } else { throw handleError(response, body); } } } catch (Exception e) { if(this.logger != null) { this.logger.severe("Unable to connect to API. Please check that your secret key is correct."); } return null; } }