// Such tests assert that no matter how we implement our REST api:
  // Retrofit or not
  // OkHttp or not
  // It should handle error responses too.
  @Test
  public void items_shouldThrowExceptionIfWebServerRespondError() {
    for (Integer errorCode : HttpCodes.clientAndServerSideErrorCodes()) {
      mockWebServer.enqueue(new MockResponse().setStatus("HTTP/1.1 " + errorCode + " Not today"));

      try {
        qualityMattersRestApi.items().toBlocking().value();
        fail("HttpException should be thrown for error code: " + errorCode);
      } catch (RuntimeException expected) {
        HttpException httpException = (HttpException) expected.getCause();
        assertThat(httpException.code()).isEqualTo(errorCode);
        assertThat(httpException.message()).isEqualTo("Not today");
      }
    }
  }
Example #2
0
  private static boolean isHttpError(Throwable error) {
    if (error instanceof HttpException) {
      HttpException httpError = (HttpException) error;
      String errorBody = "";
      try {
        Reader stream = httpError.response().errorBody().charStream();
        errorBody = CharStreams.toString(stream);
      } catch (IOException ignored) {
      }

      logger.warn(
          "Got http error {} {}, with body: {}", httpError.code(), httpError.message(), errorBody);

      return httpError.response().code() / 100 == 5;
    } else {
      return false;
    }
  }