ErrorParser { @Nullable public static ApiError parseError(@Nonnull Response<?> response) { if (response.isSuccessful()) { return null; } try { return parseError(response.errorBody().string(), response.code(), response.message()); } catch (IOException e) { return new ApiError(null, response.code(), "Unknown Error"); } }  @Nullable static ApiError parseError(@Nonnull Response<?> response); @Nonnull static ApiError parseError(@Nullable String errorBody, int statusCode, @Nullable String message);  }
@Test public void parseError_whenOldError_shouldReturnProperApiError() { String body = "{\"message\":\"Unable to find product thisIsNotAProductId\",\"code\":\"not_found\"}"; ApiError apiError = ErrorParser.parseError(body, 404, "Not Found"); assertThat(apiError.getMeta()).isNull(); assertError(apiError.getClientErrors(), "not_found", 404, "Unable to find product thisIsNotAProductId"); }
@Test public void parseError_whenErrorWithEmptyMeta_shouldReturnErrorWithMetaButNoCofirmation() { String body = "{\"meta\":{},\"errors\":[{\"status\":404,\"code\":\"unknown_place_id\",\"title\":\"Only " + "\\\"home\\\" and \\\"work\\\" are allowed.\"}]}"; ApiError apiError = ErrorParser.parseError(body, 404, "Not Found"); assertThat(apiError.getMeta().getSurgeConfirmation()).isNull(); assertError(apiError.getClientErrors(), "unknown_place_id", 404, "Only \"home\" and \"work\" are allowed."); }
@Test public void parseError_whenErrorWithSurge_shouldReturnFullError() { String body = "{\"meta\":{\"surge_confirmation\":{\"href\":\"https:\\/\\/api.uber.com\\/v1\\/surge-confirmations\\/a9ca7bf4-315c-4a8d-86a4-1697b7b94de4\",\"expires_at\":1464118311,\"multiplier\":2.1,\"surge_confirmation_id\":\"a9ca7bf4-315c-4a8d-86a4-1697b7b94de4\"}},\"errors\":[{\"status\":409,\"code\":\"surge\",\"title\":\"Surge pricing is currently in effect for this product.\"}]}"; ApiError apiError = ErrorParser.parseError(body, 409, "Unavailable"); SurgeConfirmation surgeConfirmation = apiError.getMeta().getSurgeConfirmation(); assertThat(surgeConfirmation.getHref()).isEqualTo("https: assertThat(surgeConfirmation.getMultiplier()).isEqualTo(2.1f); assertThat(surgeConfirmation.getExpiresAt()).isEqualTo(1464118311); assertThat(surgeConfirmation.getSurgeConfirmationId()).isEqualTo("a9ca7bf4-315c-4a8d-86a4-1697b7b94de4"); assertError(apiError.getClientErrors(), "surge", 409, "Surge pricing is currently in effect for this product."); }
@Test public void parseError_whenUnknownError_shouldReturnKnownError() { String body = "{\"error\":\"This is not a supported Error\",\"random\":\"random field\"}"; ApiError apiError = ErrorParser.parseError(body, 416, "ThisWasTheHttpMessage"); assertError(apiError.getClientErrors(), null, 416, "Unknown Error"); }
@Test public void parseError_whenSuccessfulResponse_shouldReturnNull() { ApiError apiError = ErrorParser.parseError(null, 404, "Not Found"); assertThat(apiError.getMeta()).isNull(); assertError(apiError.getClientErrors(), null, 404, "Not Found"); }