retrofit2.adapter.rxjava.HttpException Java Examples

The following examples show how to use retrofit2.adapter.rxjava.HttpException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OperatorMapResponseToBodyOrError.java    From Ticket-Analysis with MIT License 6 votes vote down vote up
@Override public Subscriber<? super Response<T>> call(final Subscriber<? super T> child) {
    return new Subscriber<Response<T>>(child) {
        @Override public void onNext(Response<T> response) {
            if (response.isSuccessful()) {
                child.onNext(response.body());
            } else {
                child.onError(new HttpException(response));
            }
        }

        @Override public void onCompleted() {
            child.onCompleted();
        }

        @Override public void onError(Throwable e) {
            child.onError(e);
        }
    };
}
 
Example #2
Source File: SignInActivityTest.java    From ribot-app-android with Apache License 2.0 6 votes vote down vote up
@Test
public void signInFailsWithProfileNotFound() {
    main.launchActivity(SignInActivity.getStartIntent(component.getContext(), false));
    stubAccountPickerIntent();

    // Stub with http 403 error
    HttpException http403Exception = new HttpException(Response.error(403,
            ResponseBody.create(MediaType.parse("type"), "")));
    doReturn(Observable.error(http403Exception))
            .when(component.getMockDataManager())
            .signIn(mSelectedAccount);

    onView(withId(R.id.button_sign_in))
            .perform(click());
    allowPermissionsIfNeeded();

    String expectedWelcome = main.getActivity()
            .getString(R.string.error_ribot_profile_not_found, mSelectedAccount.name);
    onView(withText(expectedWelcome))
            .check(matches(isDisplayed()));
}
 
Example #3
Source File: MainViewModelTest.java    From archi with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSearchInvalidUsername() {
    String username = "invalidUsername";
    TextView textView = new TextView(application);
    textView.setText(username);
    HttpException mockHttpException =
            new HttpException(Response.error(404, mock(ResponseBody.class)));
    when(githubService.publicRepositories(username))
            .thenReturn(Observable.<List<Repository>>error(mockHttpException));

    mainViewModel.onSearchAction(textView, EditorInfo.IME_ACTION_SEARCH, null);
    verify(dataListener, never()).onRepositoriesChanged(anyListOf(Repository.class));
    assertEquals(mainViewModel.infoMessage.get(),
            application.getString(R.string.error_username_not_found));
    assertEquals(mainViewModel.infoMessageVisibility.get(), View.VISIBLE);
    assertEquals(mainViewModel.progressVisibility.get(), View.INVISIBLE);
    assertEquals(mainViewModel.recyclerViewVisibility.get(), View.INVISIBLE);
}
 
Example #4
Source File: RetrofitRetryStaleProxyTest.java    From kaif-android with Apache License 2.0 6 votes vote down vote up
@Test
public void access_network_error_and_cache_miss() {
  when(mockRetrofitHolder.create(Foo$$RetryStale.class)).thenReturn(target);
  when(target.foo1("example")).thenReturn(Observable.error(
      new HttpException(Response.error(404,
          ResponseBody.create(MediaType.parse("application/json"), "{}")))));

  when(target.foo1$$RetryStale("example")).thenReturn(Observable.error(
      new HttpException(Response.error(501,
          ResponseBody.create(MediaType.parse("application/json"), "{}")))));

  Foo foo = retrofitRetryStaleProxy.create(Foo.class);
  try {
    foo.foo1("example").toBlocking().single();
    fail();
  } catch (Exception expected) {
    assertEquals(HttpException.class, expected.getCause().getClass());
  }
}
 
Example #5
Source File: UserRepositoryImplTest.java    From GithubUsersSearchApp with Apache License 2.0 6 votes vote down vote up
@Test
public void searchUsers_OtherHttpError_SearchTerminatedWithError() {
    //Given
    when(githubUserRestService.searchGithubUsers(anyString())).thenReturn(get403ForbiddenError());

    //When
    TestSubscriber<List<User>> subscriber = new TestSubscriber<>();
    userRepository.searchUsers(USER_LOGIN_RIGGAROO).subscribe(subscriber);

    //Then
    subscriber.awaitTerminalEvent();
    subscriber.assertError(HttpException.class);

    verify(githubUserRestService).searchGithubUsers(USER_LOGIN_RIGGAROO);

    verify(githubUserRestService, never()).getUser(USER_LOGIN_RIGGAROO);
    verify(githubUserRestService, never()).getUser(USER_LOGIN_2_REBECCA);
}
 
Example #6
Source File: RxRetrofitInterceptorTest.java    From Mockery with Apache License 2.0 6 votes vote down vote up
@Test public void When_Call_OnIllegalMock_If_Method_Return_Type_Is_Observable_Then_Get_Error_Observable()
    throws NoSuchMethodException, IOException {
  Method method = Providers.class.getDeclaredMethod("observable");
  RxRetrofit annotation = PlaceholderRetrofitAnnotation.class.getAnnotation(RxRetrofit.class);
  Metadata<RxRetrofit> metadata = new Metadata(Providers.class,
      method, null, annotation, method.getGenericReturnType());

  Observable observable = rxRetrofitInterceptor.onIllegalMock(new AssertionError(), metadata);
  TestSubscriber<List<Mock>> subscriber = new TestSubscriber();
  observable.subscribe(subscriber);
  subscriber.awaitTerminalEvent();
  subscriber.assertNoValues();

  HttpException httpException = (HttpException) subscriber.getOnErrorEvents().get(0);
  assertThat(httpException.getMessage(), is("HTTP 404 null"));
}
 
Example #7
Source File: RetryStaleHandler.java    From kaif-android with Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  MethodInfo methodInfo = getTargetMethodInfo(method);
  if (methodInfo.canRetry()) {
    Observable result = (Observable) methodInfo.invoke(target, args);
    return result.onErrorResumeNext((Func1<Throwable, Observable>) throwable -> {
      if (throwable instanceof HttpException) {
        try {
          return (Observable) getTargetCacheMethod(method).invoke(target, args);
        } catch (Exception e) {
          return Observable.error(throwable);
        }
      }
      return Observable.error(throwable);
    });
  }

  return methodInfo.invoke(target, args);
}
 
Example #8
Source File: OkApiServiceIntegrationTest.java    From Forage with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void searchAndRetrieve_shouldThrowExceptionOnWebserverError() {
    for (Integer errorCode : HttpCodes.clientAndServerSideErrorCodes()) {
        mockWebServer.enqueue(new MockResponse().setStatus("HTTP/1.1 " + errorCode + " Nope!"));

        try {
            // Input fake data to the API call
            okApiService.searchAndRetrieve("", "", "", "", false, "").toBlocking().value();
            assert_().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("Nope!");
        }
    }
}
 
Example #9
Source File: RestApiTest.java    From Mockery with Apache License 2.0 5 votes vote down vote up
@Test public void modelWithParamsFailsWhenInvalidRequestBody() {
  RequestBody requestBody = RequestBody
      .create(MediaType.parse("text/plain"), "{\"s1\":\"\"}");

  TestSubscriber<Model> subscriber = new TestSubscriber<>();
  restApi.modelWithParams(requestBody, 0).subscribe(subscriber);
  subscriber.awaitTerminalEvent();
  subscriber.assertNoValues();
  subscriber.assertError(HttpException.class);

  Throwable error = subscriber.getOnErrorEvents().get(0);
  assertThat(error.getMessage(), is("HTTP 404 null"));
}
 
Example #10
Source File: SignInPresenterTest.java    From ribot-app-android with Apache License 2.0 5 votes vote down vote up
@Test
public void signInFailedWithRibotProfileNotFoundError() {
    //Stub mock data manager
    HttpException http403Exception = new HttpException(Response.error(403,
            ResponseBody.create(MediaType.parse("type"), "")));
    stubDataManagerSignIn(Observable.error(http403Exception));

    mSignInPresenter.signInWithGoogle(mAccount);
    //Check that the right methods are called
    verify(mMockSignInMvpView).showProgress(true);
    verify(mMockSignInMvpView).setSignInButtonEnabled(true);
    verify(mMockSignInMvpView).showProfileNotFoundError(mAccount.name);
    verify(mMockSignInMvpView).showProgress(false);
    verify(mMockSignInMvpView).setSignInButtonEnabled(false);
}
 
Example #11
Source File: RestApiTest.java    From Mockery with Apache License 2.0 5 votes vote down vote up
@Test public void modelsWithParamFailsWhenInvalidJson() {
  String json = "";

  TestSubscriber<List<Model>> subscriber = new TestSubscriber<>();
  restApi.modelsWithParam(json).subscribe(subscriber);
  subscriber.awaitTerminalEvent();
  subscriber.assertNoValues();
  subscriber.assertError(HttpException.class);

  Throwable error = subscriber.getOnErrorEvents().get(0);
  assertThat(error.getMessage(), is("HTTP 404 null"));
}
 
Example #12
Source File: GithubRepositoryTest.java    From AndroidSchool with Apache License 2.0 5 votes vote down vote up
@Test
public void testErrorAuth() throws Exception {
    RepositoryProvider.provideKeyValueStorage().saveToken(ERROR);
    TestSubscriber<Authorization> testSubscriber = new TestSubscriber<>();
    mRepository.auth("error", "12").subscribe(testSubscriber);

    testSubscriber.assertError(HttpException.class);

    KeyValueStorage storage = RepositoryProvider.provideKeyValueStorage();
    assertEquals("", storage.getToken());
    assertEquals("", storage.getUserName().toBlocking().first());
}
 
Example #13
Source File: FactoryException.java    From Rx-Retrofit with MIT License 5 votes vote down vote up
/**
 * 解析异常
 *
 * @param e
 * @return
 */
public static ApiException analysisExcetpion(Throwable e) {
    ApiException apiException = new ApiException(e);
    if (e instanceof HttpException) {
         /*网络异常*/
        apiException.setCode(CodeException.HTTP_ERROR);
        apiException.setDisplayMessage(HttpException_MSG);
    } else if (e instanceof HttpTimeException) {
         /*自定义运行时异常*/
        HttpTimeException exception = (HttpTimeException) e;
        apiException.setCode(CodeException.RUNTIME_ERROR);
        apiException.setDisplayMessage(exception.getMessage());
    } else if (e instanceof ConnectException||e instanceof SocketTimeoutException) {
         /*链接异常*/
        apiException.setCode(CodeException.HTTP_ERROR);
        apiException.setDisplayMessage(ConnectException_MSG);
    } else if ( e instanceof JSONException || e instanceof ParseException) {
         /*json解析异常*/
        apiException.setCode(CodeException.JSON_ERROR);
        apiException.setDisplayMessage(JSONException_MSG);
    }else if (e instanceof UnknownHostException){
        /*无法解析该域名异常*/
        apiException.setCode(CodeException.UNKOWNHOST_ERROR);
        apiException.setDisplayMessage(UnknownHostException_MSG);
    } else {
        /*未知异常*/
        apiException.setCode(CodeException.UNKNOWN_ERROR);
        apiException.setDisplayMessage(e.getMessage());
    }
    return apiException;
}
 
Example #14
Source File: FactoryException.java    From RxRetrofit-mvp with MIT License 5 votes vote down vote up
/**
 * 解析异常
 *
 * @param e
 * @return
 */
public static ApiException analysisExcetpion(Throwable e) {
    ApiException apiException = new ApiException(e);
    if (e instanceof HttpException) {
         /*网络异常*/
        apiException.setCode(CodeException.HTTP_ERROR);
        apiException.setDisplayMessage(HttpException_MSG);
    } else if (e instanceof HttpTimeException) {
         /*自定义运行时异常*/
        HttpTimeException exception = (HttpTimeException) e;
        apiException.setCode(CodeException.RUNTIME_ERROR);
        apiException.setDisplayMessage(exception.getMessage());
    } else if (e instanceof ConnectException||e instanceof SocketTimeoutException) {
         /*链接异常*/
        apiException.setCode(CodeException.HTTP_ERROR);
        apiException.setDisplayMessage(ConnectException_MSG);
    } else if (e instanceof JSONPathException || e instanceof JSONException || e instanceof ParseException) {
         /*fastjson解析异常*/
        apiException.setCode(CodeException.JSON_ERROR);
        apiException.setDisplayMessage(JSONException_MSG);
    }else if (e instanceof UnknownHostException){
        /*无法解析该域名异常*/
        apiException.setCode(CodeException.UNKOWNHOST_ERROR);
        apiException.setDisplayMessage(UnknownHostException_MSG);
    } else {
        /*未知异常*/
        apiException.setCode(CodeException.UNKNOWN_ERROR);
        apiException.setDisplayMessage(e.getMessage());
    }
    return apiException;
}
 
Example #15
Source File: NetUtil.java    From Anago with Apache License 2.0 5 votes vote down vote up
/**
 * RxJavaの返すExceptionをGitHub APIのエラーに変換する
 * それ以外のエラーの場合、nullを返す
 * @param throwable
 * @return
 */
public static Error convertError(Throwable throwable) {
    try {
        if (throwable instanceof HttpException) {
            HttpException exception = (HttpException) throwable;
            ResponseBody responseBody = exception.response().errorBody();
            Error error = new Gson().fromJson(responseBody.string(), Error.class);
            return error;
        }
    } catch (IOException e) {
        // do nothing
    }
    return null;
}
 
Example #16
Source File: RetrofitRetryStaleProxyTest.java    From kaif-android with Apache License 2.0 5 votes vote down vote up
@Test
public void access_network_error() {
  when(mockRetrofitHolder.create(Foo$$RetryStale.class)).thenReturn(target);
  when(target.foo1("example")).thenReturn(Observable.error(
      new HttpException(Response.error(404,
          ResponseBody.create(MediaType.parse("application/json"), "{}"))))
  );
  when(target.foo1$$RetryStale("example")).thenReturn(Observable.just("success"));

  Foo foo = retrofitRetryStaleProxy.create(Foo.class);
  assertEquals("success", foo.foo1("example").toBlocking().single());
}
 
Example #17
Source File: RetrofitRetryStaleProxyTest.java    From kaif-android with Apache License 2.0 5 votes vote down vote up
@Test
public void access_no_cache_retry_method() {
  when(mockRetrofitHolder.create(Foo$$RetryStale.class)).thenReturn(target);
  when(target.foo3("example")).thenReturn(Observable.error(
      new HttpException(Response.error(404,
          ResponseBody.create(MediaType.parse("application/json"), "{}")))));

  Foo foo = retrofitRetryStaleProxy.create(Foo.class);
  try {
    foo.foo3("example").toBlocking().single();
    fail();
  } catch (Exception expected) {
    assertEquals(HttpException.class, expected.getCause().getClass());
  }
}
 
Example #18
Source File: MainPresenterTest.java    From archi with Apache License 2.0 5 votes vote down vote up
@Test
public void loadRepositoriesCallsShowMessage_withUsernameNotFoundString() {
    String username = "ivacf";
    HttpException mockHttpException =
            new HttpException(Response.error(404, mock(ResponseBody.class)));
    when(githubService.publicRepositories(username))
            .thenReturn(Observable.<List<Repository>>error(mockHttpException));

    mainPresenter.loadRepositories(username);
    verify(mainMvpView).showProgressIndicator();
    verify(mainMvpView).showMessage(R.string.error_username_not_found);
}
 
Example #19
Source File: AppException.java    From FriendBook with GNU General Public License v3.0 5 votes vote down vote up
public static String getExceptionMessage(Throwable throwable) {
    String message;
    if (throwable instanceof ApiException) {
        message = throwable.getMessage();
    } else if (throwable instanceof SocketTimeoutException) {
        message = "网络连接超时,请稍后再试";
    } else if (throwable instanceof ConnectException) {
        message = "网络连接失败,请稍后再试";
    } else if (throwable instanceof HttpException||throwable instanceof retrofit2.HttpException) {
        message = "网络出错,请稍后再试";
    } else if (throwable instanceof UnknownHostException || throwable instanceof NetNotConnectedException) {
        message = "当前无网络,请检查网络设置";
    } else if (throwable instanceof SecurityException) {
        message = "系统权限不足";
    } else if (throwable instanceof JsonParseException
            || throwable instanceof JSONException
            || throwable instanceof ParseException) {
        message = "数据解析错误";
    } else if (throwable instanceof javax.net.ssl.SSLHandshakeException) {
        message = "网络证书验证失败";
    } else {
        message = throwable.getMessage();
        if (message==null||message.length() <= 40) {
            message = "出错了 ≥﹏≤ ,请稍后再试";
        }
    }
    return message;
}
 
Example #20
Source File: FactoryException.java    From RxjavaRetrofitDemo-string-master with MIT License 5 votes vote down vote up
/**
 * 解析异常
 *
 * @param e
 * @return
 */
public static ApiException analysisExcetpion(Throwable e) {
    ApiException apiException = new ApiException(e);
    if (e instanceof HttpException) {
         /*网络异常*/
        apiException.setCode(CodeException.HTTP_ERROR);
        apiException.setDisplayMessage(HttpException_MSG);
    } else if (e instanceof HttpTimeException) {
         /*自定义运行时异常*/
        HttpTimeException exception = (HttpTimeException) e;
        apiException.setCode(CodeException.RUNTIME_ERROR);
        apiException.setDisplayMessage(exception.getMessage());
    } else if (e instanceof ConnectException||e instanceof SocketTimeoutException) {
         /*链接异常*/
        apiException.setCode(CodeException.HTTP_ERROR);
        apiException.setDisplayMessage(ConnectException_MSG);
    } else if ( e instanceof JSONException || e instanceof ParseException) {
        apiException.setCode(CodeException.JSON_ERROR);
        apiException.setDisplayMessage(JSONException_MSG);
    }else if (e instanceof UnknownHostException){
        /*无法解析该域名异常*/
        apiException.setCode(CodeException.UNKOWNHOST_ERROR);
        apiException.setDisplayMessage(UnknownHostException_MSG);
    } else {
        /*未知异常*/
        apiException.setCode(CodeException.UNKNOWN_ERROR);
        apiException.setDisplayMessage(e.getMessage());
    }
    return apiException;
}
 
Example #21
Source File: BroadcastManager.java    From LQRWeChat with MIT License 5 votes vote down vote up
/**
 * 发送广播
 *
 * @param action 唯一码
 * @param obj    参数
 */
public void sendBroadcastWithObjct(String action, Object obj) {
    try {
        Intent intent = new Intent();
        intent.setAction(action);
        intent.putExtra("result", JsonMananger.beanToJson(obj));
        mContext.sendBroadcast(intent);
    } catch (HttpException e) {
        e.printStackTrace();
    }
}
 
Example #22
Source File: ErrorResolver.java    From hyperledger-java with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve error.
 *
 * @param throwable throwable
 * @param tClass    tClass
 * @param <T>       T
 * @return T
 */
@SuppressWarnings("unchecked")
public static <T> T resolve(Throwable throwable, Class<T> tClass) {
    HttpException exception = (HttpException) throwable;
    Converter<ResponseBody, ?> converter = Hyperledger.CONVERTER_FACTORY.responseBodyConverter(tClass, null, null);
    try (ResponseBody responseBody = exception.response().errorBody()) {
        return (T) converter.convert(responseBody);
    } catch (IOException e) {
        LOG.error("", e);
        throw new RuntimeException(e);
    }
}
 
Example #23
Source File: LogPresenterTest.java    From Forage with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void submitLog_onHttpError() {
    when(networkInteractor.hasInternetConnectionCompletable()).thenReturn(Completable.complete());

    HttpException exception = new HttpException(Response.error(404, mock(ResponseBody.class)));
    Single<SubmitLogResponse> single = Single.error(exception);
    when(okApiInteractor.submitLog(anyString(), anyString(), anyString()))
            .thenReturn(single);

    logPresenter.submitLog("", "", "");

    verify(view, times(1)).showSubmittingDialog();
    verify(view, times(1)).showErrorDialog(exception.getMessage());
}
 
Example #24
Source File: LogPresenter.java    From Forage with Mozilla Public License 2.0 5 votes vote down vote up
public void submitLog(final String cacheCode, final String comment, final String type) {
    networkInteractor.hasInternetConnectionCompletable()
            .andThen(okApiInteractor.submitLog(cacheCode, type, comment))
            .compose(RxDelay.delaySingle(getViewState()))
            .doOnSubscribe(() -> {
                if (isViewAttached()) {
                    view.showSubmittingDialog();
                }
            })
            .subscribe(submitLogResponse -> {
                        if (isViewAttached()) {
                            if (submitLogResponse.isSuccessful) {
                                view.showSuccessfulSubmit();
                            } else {
                                view.showErrorDialog(submitLogResponse.message);
                            }
                        }
                    },
                    throwable -> {
                        if (isViewAttached()) {
                            if (throwable instanceof NetworkUnavailableException) {
                                view.showErrorInternetDialog();
                            } else if (throwable instanceof HttpException) { // Non-200 HTTP Code
                                HttpException httpException = ((HttpException) throwable);
                                view.showErrorDialog(httpException.getMessage());
                            } else {
                                view.showErrorDialog(R.string.log_submit_error_unknown);
                            }
                        }
                    }
            );
}
 
Example #25
Source File: V3.java    From aptoide-client-v8 with GNU General Public License v3.0 5 votes vote down vote up
@Override public Observable<U> observe(boolean bypassCache) {
  return bodyInterceptor.intercept(map)
      .flatMapObservable(body -> super.observe(bypassCache)
          .onErrorResumeNext(throwable -> {
            if (throwable instanceof HttpException) {
              try {

                GenericResponseV3 genericResponseV3 =
                    (GenericResponseV3) converterFactory.responseBodyConverter(
                        GenericResponseV3.class, null, null)
                        .convert(((HttpException) throwable).response()
                            .errorBody());

                if (INVALID_ACCESS_TOKEN_CODE.equals(genericResponseV3.getError())) {

                  if (!accessTokenRetry) {
                    accessTokenRetry = true;
                    return tokenInvalidator.invalidateAccessToken()
                        .andThen(V3.this.observe(bypassCache));
                  }
                } else {
                  AptoideWsV3Exception exception = new AptoideWsV3Exception(throwable);
                  exception.setBaseResponse(genericResponseV3);
                  return Observable.error(exception);
                }
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
            return Observable.error(throwable);
          }));
}
 
Example #26
Source File: MainPresenter.java    From android-base-mvp with Apache License 2.0 4 votes vote down vote up
private static boolean isHttp404(Throwable error) {
    return error instanceof HttpException && ((HttpException) error).code() == 404;
}
 
Example #27
Source File: ExceptionHandle.java    From xifan with Apache License 2.0 4 votes vote down vote up
public static ApiException handleException(Throwable e) {
    e.printStackTrace();
    Logger.e("http request error result:\n" + e.fillInStackTrace());
    Context context = App.getInstance().getApplicationContext();

    if (e instanceof HttpException) {
        ApiException apiException = null;
        HttpException httpException = (HttpException) e;
        String errorMessage = null;
        switch (httpException.code()) {
            case UNAUTHORIZED:
                errorMessage = context.getString(R.string.http_unauthorized_error);
                break;
            case FORBIDDEN:
            case NOT_FOUND:
            case REQUEST_TIMEOUT:
            case RANGE_NOT_SATISFIABLE:
            case INTERNAL_SERVER_ERROR:
            case BAD_GATEWAY:
            case SERVICE_UNAVAILABLE:
            case GATEWAY_TIMEOUT:
                errorMessage = context.getString(R.string.http_service_error);
                break;
        }

        try {
            String errorBody = httpException.response().errorBody().string();
            if (!TextUtils.isEmpty(errorBody)) {
                errorMessage = errorBody;
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        apiException = new ApiException(ErrorCode.ERROR_UNAUTHORIZED, errorMessage);
        return apiException;
    }

    if (e instanceof ConnectException) {
        return new ApiException(ErrorCode.ERROR_NO_CONNECT,
                context.getString(R.string.http_connect_error));
    }

    if (e instanceof JsonParseException || e instanceof JsonSyntaxException) {
        return new ApiException(ErrorCode.ERROR_PARSE,
                context.getString(R.string.http_data_parse_error));
    }

    if (e instanceof SocketTimeoutException) {
        return new ApiException(ErrorCode.ERROR_NET_TIMEOUT,
                context.getString(R.string.http_connect_timeout));
    }
    return new ApiException(ErrorCode.ERROR_UNKNOWN,
            context.getString(R.string.http_unknow_error));
}
 
Example #28
Source File: NetworkUtil.java    From ribot-app-android with Apache License 2.0 4 votes vote down vote up
/**
 * Returns true if the Throwable is an instance of RetrofitError with an
 * http status code equals to the given one.
 */
public static boolean isHttpStatusCode(Throwable throwable, int statusCode) {
    return throwable instanceof HttpException
            && ((HttpException) throwable).code() == statusCode;
}
 
Example #29
Source File: MainActivity.java    From archi with Apache License 2.0 4 votes vote down vote up
public void loadGithubRepos(String username) {
    progressBar.setVisibility(View.VISIBLE);
    reposRecycleView.setVisibility(View.GONE);
    infoTextView.setVisibility(View.GONE);
    ArchiApplication application = ArchiApplication.get(this);
    GithubService githubService = application.getGithubService();
    subscription = githubService.publicRepositories(username)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(application.defaultSubscribeScheduler())
            .subscribe(new Subscriber<List<Repository>>() {
                @Override
                public void onCompleted() {
                    progressBar.setVisibility(View.GONE);
                    if (reposRecycleView.getAdapter().getItemCount() > 0) {
                        reposRecycleView.requestFocus();
                        hideSoftKeyboard();
                        reposRecycleView.setVisibility(View.VISIBLE);
                    } else {
                        infoTextView.setText(R.string.text_empty_repos);
                        infoTextView.setVisibility(View.VISIBLE);
                    }
                }

                @Override
                public void onError(Throwable error) {
                    Log.e(TAG, "Error loading GitHub repos ", error);
                    progressBar.setVisibility(View.GONE);
                    if (error instanceof HttpException
                            && ((HttpException) error).code() == 404) {
                        infoTextView.setText(R.string.error_username_not_found);
                    } else {
                        infoTextView.setText(R.string.error_loading_repos);
                    }
                    infoTextView.setVisibility(View.VISIBLE);
                }

                @Override
                public void onNext(List<Repository> repositories) {
                    Log.i(TAG, "Repos loaded " + repositories);
                    RepositoryAdapter adapter =
                            (RepositoryAdapter) reposRecycleView.getAdapter();
                    adapter.setRepositories(repositories);
                    adapter.notifyDataSetChanged();
                }
            });
}
 
Example #30
Source File: MainPresenter.java    From archi with Apache License 2.0 4 votes vote down vote up
private static boolean isHttp404(Throwable error) {
    return error instanceof HttpException && ((HttpException) error).code() == 404;
}