@Test public void searchUsers_OtherHttpError_SearchTerminatedWithError() { //Given when(githubUserRestService.searchGithubUsers(anyString())).thenReturn(get403ForbiddenError()); //When TestSubscriber<List<User>> subscriber = new TestSubscriber<>(); userRepository.searchUsers(USER_LOGIN_MOYHEEN).subscribe(subscriber); //Then subscriber.awaitTerminalEvent(); subscriber.assertError(HttpException.class); verify(githubUserRestService).searchGithubUsers(USER_LOGIN_MOYHEEN); verify(githubUserRestService, never()).getUser(USER_LOGIN_MOYHEEN); verify(githubUserRestService, never()).getUser(USER_LOGIN_2_MOYHEEN); }
public static void onLogInError(Throwable e) { if (e instanceof HttpException) { int code = ((HttpException) e).code(); switch (code) { case 403: ToastUtil.showShort(R.string.wrong_password); break; case 404: ToastUtil.showShort(R.string.user_not_exist); break; case 409: ToastUtil.showShort(R.string.user_already_exist); break; default: ToastUtil.showShort(R.string.network_failure); break; } } else { if (TextUtils.isEmpty(e.getMessage())) { ToastUtil.showShort(R.string.network_failure); } else { ToastUtil.showShort(e.getMessage()); } } e.printStackTrace(); }
public static void onUploadError(Throwable e) { if (e instanceof HttpException) { int code = ((HttpException) e).code(); switch (code) { case 404: ToastUtil.showShort(R.string.file_wrong_upload); break; case 409: ToastUtil.showShort(R.string.name_already_exist); break; default: ToastUtil.showShort(R.string.network_failure); break; } } else { if (TextUtils.isEmpty(e.getMessage())) { ToastUtil.showShort(R.string.network_failure); } else { ToastUtil.showShort(e.getMessage()); } } e.printStackTrace(); }
@Override public void onError(Throwable e) { e.printStackTrace(); if (e instanceof HttpException) { HttpException httpException = (HttpException) e; //httpException.response().errorBody().string() int code = httpException.code(); String msg = httpException.getMessage(); if (code == 504) { msg = "网络不给力"; } if (code == 502 || code == 404) { msg = "服务器异常,请稍后再试"; } onFailure(msg); } else { onFailure(e.getMessage()); } onFinish(); }
@Test public void searchMakeUp_OtherHttpError_searchTerminatedWithError() { // Given when(makeUpProductRestService.searchMakeUpProducts(anyString(), anyString())).thenReturn (get403ForbiddenError().toList()); // When TestSubscriber<List<MakeUp>> subscriber = new TestSubscriber<>(); makeUpRepository.searchMakeUp(BRAND_COVERGIRL, PRODUCT_TYPE_LIPSTICK).subscribe(subscriber); // Then subscriber.awaitTerminalEvent(); subscriber.assertError(HttpException.class); verify(makeUpProductRestService).searchMakeUpProducts(BRAND_COVERGIRL, PRODUCT_TYPE_LIPSTICK); }
@Test public void groupApishouldReturnBadRequest() { // Given login = "wrongLogin"; password = "wrongPassword"; TestSubscriber<SigfoxData<Group>> testObserver = new TestSubscriber<>(); // When sigfoxClient.getGroupList(null, null, null).subscribe(testObserver); // Then testObserver.assertError(HttpException.class); List<Throwable> errorEvents = testObserver.getOnErrorEvents(); assertThat(errorEvents).isNotNull().isNotEmpty(); assertThat(errorEvents.get(0)).hasMessage("HTTP 400 Bad Request"); }
@Test public void checkFailureSessionRequestBehavior(){ PowerMockito.mockStatic(ErrorMessageFactory.class); when(ErrorMessageFactory.createMessageOnLogin(any(), any())).thenReturn(""); when(sessionService .getSession(any(SessionRequest.class))) .thenReturn(Observable.error(new HttpException( Response.error(422, ResponseBody.create(null, new byte[0]))) )); // presenter.requestSession(); verify(getTokenUseCase).execute(any(Subscriber.class)); verify(sessionRepository).getSession(); verify(sessionService).getSession(any(SessionRequest.class)); verify(view).showError(anyString()); }
@Test public void checkLoginErrorMessages(){ String message = ErrorMessageFactory.createMessageOnLogin( context, new IllegalStateException()); Assert.assertEquals(message, wrongLoginOrPassword); message = ErrorMessageFactory.createMessageOnLogin( context, new HttpException(Response.error(401, ResponseBody.create(null, new byte[0])))); Assert.assertEquals(message, sessionExpired); message = ErrorMessageFactory.createMessageOnLogin( context, new HttpException(Response.error(500, ResponseBody.create(null, new byte[0])))); Assert.assertEquals(message, serverCommonError); message = ErrorMessageFactory.createMessageOnLogin( context, new HttpException(Response.error(503, ResponseBody.create(null, new byte[0])))); Assert.assertEquals(message, serverIsBusy); message = ErrorMessageFactory.createMessageOnLogin(context, new IOException()); Assert.assertEquals(message, messageNoConnection); }
@Test public void checkRegistrationErrorMessages(){ String message = ErrorMessageFactory.createMessageOnRegistration( context, new HttpException(Response.error(422, ResponseBody.create(null, new byte[0])))); Assert.assertEquals(message, userExists); message = ErrorMessageFactory.createMessageOnRegistration( context, new HttpException(Response.error(401, ResponseBody.create(null, new byte[0])))); Assert.assertEquals(message, sessionExpired); message = ErrorMessageFactory.createMessageOnRegistration( context, new HttpException(Response.error(500, ResponseBody.create(null, new byte[0])))); Assert.assertEquals(message, serverCommonError); message = ErrorMessageFactory.createMessageOnRegistration( context, new HttpException(Response.error(503, ResponseBody.create(null, new byte[0])))); Assert.assertEquals(message, serverIsBusy); message = ErrorMessageFactory.createMessageOnRegistration(context, new IOException()); Assert.assertEquals(message, messageNoConnection); }
@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); }
@Override public void onError(Throwable e) { if (e instanceof HttpException) { Toast.makeText(mContext, "网络连接不可用,请检查网络设置", Toast.LENGTH_SHORT).show(); } else if (e instanceof UnknownHostException) { Toast.makeText(mContext, "网络连接不可用,请检查网络设置", Toast.LENGTH_SHORT).show(); } else if (e instanceof WebResponseException) { Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show(); } else if (e instanceof TokenExpriedException) { Toast.makeText(mContext, "Token 失效,请重新登录", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(); intent.setClass(mContext, LoginActivity.class); mContext.startActivity(intent); } else { Timber.e(e, "Subscriber onError"); } }
/** * Test demonstrates the usage of {@link com.rzagorski.retrofitrxerrorhandler.backoff.strategies.Simple} * backoff strategy. The server responds with 500 server error every time. The backoff strategy * is executed and after {@link com.rzagorski.retrofitrxerrorhandler.backoff.strategies.Simple.Builder#setMaxRetries(int)} * is run out, the appropriate error is passed to client. * 4 times 10 second timeout. * <br></br> * Test created by Robert Zagorski on 19.10.2016 */ @Test public void testBackoffCompletes1() throws Exception { mockWebServer.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { return new MockResponse().setResponseCode(500); } }); RxCallAdapter rxCallAdapter = new RxCallAdapter.Builder() .addBackoffStrategy(Simple.init() .addHttpCode(500) .setMaxRetries(300).build()) .build(); GitHub github = createRetrofitInstance(mockWebServer.url("/").toString(), new RxErrorHandingFactory(rxCallAdapter)); Observable observable = github.repos("square"); TestSubscriber testSubscriber = new TestSubscriber(); observable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); testSubscriber.assertError(HttpException.class); }
@Test public void testBackoffCompletes() throws Exception { mockWebServer.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { return MockWebServerUtils.getSuccessfulResponse(); } }); RxCallAdapter rxCallAdapter = new RxCallAdapter.Builder() .addBackoffStrategy(Exponential.init() .addThrowable(HttpException.class) .setMaxRetries(3).build()) .build(); GitHub github = createRetrofitInstance(mockWebServer.url("/").toString(), new RxErrorHandingFactory(rxCallAdapter)); Observable observable = github.repos("square"); TestSubscriber testSubscriber = new TestSubscriber(); observable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); testSubscriber.assertCompleted(); }
@Test public void testBackoffError1() throws Exception { mockWebServer.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { return new MockResponse().setResponseCode(500); } }); RxCallAdapter rxCallAdapter = new RxCallAdapter.Builder() .addBackoffStrategy(Exponential.init() .addThrowable(HttpException.class) .setMaxRetries(3).build()) .setLoggingEnabled(true) .build(); GitHub github = createRetrofitInstance(mockWebServer.url("/").toString(), new RxErrorHandingFactory(rxCallAdapter)); Observable observable = github.repos("square"); TestSubscriber testSubscriber = new TestSubscriber(); observable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); assertTrue(testSubscriber.getOnErrorEvents().size() == 1); }
@Test public void testBackoffError2() throws Exception { mockWebServer.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { return new MockResponse().setResponseCode(500); } }); RxCallAdapter rxCallAdapter = new RxCallAdapter.Builder() .addBackoffStrategy(Exponential.init() .addThrowable(HttpException.class) .setMaxRetries(3).build()) .setLoggingEnabled(true) .build(); GitHub github = createRetrofitInstance(mockWebServer.url("/").toString(), new RxErrorHandingFactory(rxCallAdapter)); long startTime = System.currentTimeMillis(); Observable observable = github.repos("square"); TestSubscriber testSubscriber = new TestSubscriber(); observable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); long endTime = System.currentTimeMillis(); System.out.println((endTime - startTime)); assertTrue((endTime - startTime) >= 13 * MockWebServerUtils.ONE_SEC); }
@Override public void onError(Throwable e) { e.printStackTrace(); String msg; if (e instanceof HttpException) { HttpException httpException = (HttpException) e; //httpException.response().errorBody().string() int code = httpException.code(); msg = httpException.getMessage(); if (code == 504) { msg = "网络不给力"; } apiCallback.onFailure(code, msg); } else if (e instanceof SocketTimeoutException) { msg = "服务器连接超时"; apiCallback.onFailure(GankError.ERROR_TIMEOUT, msg + "\r\n" + e.getMessage()); } else if (e instanceof UnknownHostException) { msg = "未知主机地址错误"; apiCallback.onFailure(GankError.ERROR_UNKNOWHOST, msg + "\r\n" + e.getMessage()); } else { msg = e.getMessage(); apiCallback.onFailure(GankError.ERROR_EXCEPTION, msg + "\r\n" + e.getMessage()); } apiCallback.onCompleted(); }
@Override public HttpResult<T> call(Throwable throwable) { Log.d("postOrder", throwable.toString()); HttpResult<T> responseError = null; if (throwable instanceof HttpException) { try { String errorBody = ((HttpException) throwable).response().errorBody().string(); Type type = new TypeToken<HttpResult<ResponseBody>>() { }.getType(); responseError = new Gson().fromJson(errorBody, type); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(throwable.getMessage()); } } return responseError; }
@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!"); } } }
@Override public void onError(Throwable e) { String message; Context context = ArcaneTrackerApplication.getContext(); if (e instanceof HttpException) { message = context.getString(R.string.trackobotHttpError, ((HttpException) e).code()); } else if (e instanceof SocketTimeoutException) { message = context.getString(R.string.trackobotTimeout); } else if (e instanceof ConnectException) { message = context.getString(R.string.trackobotConnectError); } else if (e instanceof IOException) { message = context.getString(R.string.trackobotNetworkError); } else { message = context.getString(R.string.trackobotError); } Toast.makeText(ArcaneTrackerApplication.getContext(), message, Toast.LENGTH_LONG).show(); Utils.reportNonFatal(e); }
/** * onError:(拦截处理错误信息). <br> * * @param ex 返回数据 * @author ysj * @since JDK 1.7 * date: 2015-12-9 下午5:20:36 <br> */ public static Throwable onError(Throwable ex) { Log.e(ex.getMessage(), ex); if (ex instanceof HttpException) { int code = ((HttpException) ex).code(); if (code >= 300 && code < 400) { return new RequestException(code, MSG_ERROR_RESPONSE_3XX); } else if (code >= 400 && code < 500) { return new RequestException(code, MSG_ERROR_RESPONSE_4XX); } else if (code >= 500 && code < 600) { return new RequestException(code, MSG_ERROR_RESPONSE_5XX); } } else if (ex instanceof SocketException) { return new RequestException(RESPONSE_STATUS_TIMEOUT, MSG_ERROR_SOCKETTIMEOUT); } else if (ex instanceof RequestException) { return ex; } else if (TextUtils.isEmpty(ex.getMessage())) { return new RequestException(2, MSG_ERROR_REQUEST); } return new RequestException(1, MSG_ERROR_REQUEST); }
public static String handelError(Throwable error) { if (isRelatedToNetwork(error)) { return App.getGlobalContext().getString(R.string.error_network_no_internet_connection); } else if (error instanceof HttpException) { try { HttpException retroError = (HttpException) error; ApiError errorObj = new Gson().fromJson(retroError.response().errorBody().charStream(), ApiError.class); return ErrorFactory.getErrorMessage(errorObj.getCode()); } catch (Throwable e) { e.printStackTrace(); } } else if (error instanceof FirebaseException) { return error.getMessage(); } return ErrorFactory.getErrorMessage(ErrorFactory.GENERAL_DEFAULT_ERROR); }
@Override public void onError(Throwable e) { if (e instanceof HttpException) { HttpException error = (HttpException) e; Log.d(TAG, "Server returned error! Code: " + error.code()); // user need relogin if (error.code() == 401) { relogin(); // dont need to continue here return; } } rescheduleFallbackPeriodicTask(); }
@Override public void onError(Throwable e) { e.printStackTrace(); if (e instanceof HttpException) { HttpException httpException = (HttpException) e; //httpException.response().errorBody().string() int code = httpException.code(); String msg = httpException.getMessage(); if (code == 504) { msg = "网络不给力"; } apiCallback.onFailure(code, msg); } else { apiCallback.onFailure(0, e.getMessage()); } apiCallback.onCompleted(); }
@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")); }
public void vote(ViewProvider provider, String itemId, final int index) { queryAPI().mutation(QueryField.vote(itemId)) .filter(newData -> newData != null) .map(newData -> newData.voteCard.card) .compose(RxMainThread.mainThread()) .subscribe(card -> updateCardItem(provider, card, index), throwable -> { if (throwable instanceof HttpException) { HttpException exception = (HttpException) throwable; if (exception.code() == 400) {// 不可以进行重复续命,不对用户做提示} } else { ToastUtils.shorts(context, throwable.getMessage()); } provider.updateCard(null, index); } }); }
@Override public void onError(Throwable e) { if (e instanceof HttpException) { executeOnLoadDataError(null); } else if (e instanceof IOException) { executeOnLoadDataError(null); } else if (e instanceof ApiException) { ApiException exception = (ApiException) e; if (exception.isTokenExpried()) { if (isAdded()) { //handle ui } } else { AppContext.toast(exception.getMessage()); } } else { executeOnLoadDataError(null); } executeOnLoadFinish(); }
@Test public void simpleErrorCase() throws IOException { TestSubscriber<TestResponse> subscriber = TestSubscriber.create(); // test simple error case server.enqueue(new MockResponse().setResponseCode(400)); service.authenticatedMethod().subscribe(subscriber); subscriber.awaitTerminalEvent(); subscriber.assertNoValues(); subscriber.assertError(HttpException.class); subscriber = TestSubscriber.create(); server.enqueue(new MockResponse().setResponseCode(400)); service.unauthenticatedMethod().subscribe(subscriber); subscriber.awaitTerminalEvent(); subscriber.assertNoValues(); subscriber.assertError(HttpException.class); }
@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); }
@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()); } }
public static NetworkErrorCode parseException(Throwable e) { if (e instanceof ConnectException) return CONNECTION_ERROR; if (e instanceof SocketTimeoutException) return SOCKET_TIMEOUT; if (e instanceof UnknownHostException) return UNKNOWN_HOST_EXCEPTION; if (ObjectUtils.Classpath.RETROFIT_RX_ADAPTER && e instanceof HttpException) { HttpException httpException = (HttpException) e; switch (httpException.code()) { case 303: return SEE_OTHER; case 401: return UNAUTHORIZED; case 403: return FORBIDDEN; case 404: return NOT_FOUND; case 409: return CONFLICT; case 500: return SERVER_ERROR; case 502: return BAD_GATEWAY; } } return CUSTOM; }
@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); }
@Override public void onError(Throwable e) { if (baseView != null) { baseView.hideLoading(); } if (e instanceof BusinessException) { } else if (e instanceof ConnectException || e instanceof SocketTimeoutException) {// 超时 baseView.onError("网络不畅,请稍后再试!"); } else if (e instanceof HttpException) {// server 异常 httpExceptionHandling(e); } else if (e instanceof JSONException || e instanceof ParseException) { baseView.onError("数据解析异常"); } else { // baseView.onError("出了点小问题"); onOtherError(e); } e.printStackTrace(); }
public void addBulletin(Bulletin bulletin) { BulletinService service = ServiceCreator.createService (BulletinService.class); Observable<String> observable = service.createBulletin("bearer " + User.getInstance().token, bulletin); observable .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( responseMsg -> mPresenter.onFinishRequest(200, responseMsg), e -> { Log.e(Config.LOG, e.getMessage()); if (e instanceof HttpException) mPresenter.onFinishRequest(((HttpException) e).code(), e.getMessage()); else mPresenter.onFinishRequest(0, e.getMessage()); } ); }
public void editBulletin(Bulletin bulletin) { BulletinService service = ServiceCreator.createService (BulletinService.class); Observable<String> observable = service.updateBulletin("bearer " + User.getInstance().token, bulletin.getId(), bulletin); observable .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( responseMsg -> mPresenter.onFinishRequest(200, responseMsg), e -> { //Log.e(Config.LOG, e.getMessage()); if (e instanceof HttpException) mPresenter.onFinishRequest(((HttpException) e).code(), e.getMessage()); else mPresenter.onFinishRequest(0, e.getMessage()); } ); }
public void deleteBulletin(String bulletinId) { BulletinService service = ServiceCreator.createService (BulletinService.class); Observable<String> observable = service.deleteBulletin("bearer " + User.getInstance().token, bulletinId); observable .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( responseMsg -> mPresenter.onFinishRequest(200, responseMsg), e -> { //Log.e(Config.LOG, e.getMessage()); if (e instanceof HttpException) mPresenter.onFinishRequest(((HttpException) e).code(), e.getMessage()); else mPresenter.onFinishRequest(0, e.getMessage()); } ); }
@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())); }
public static String getError(Throwable e, Retrofit retrofit) { String errorMessage = "General Error!"; if (e instanceof HttpException) { ResponseBody body = ((HttpException) e).response().errorBody(); Converter<ResponseBody, ApiError> responseBodyObjectConverter = retrofit.responseBodyConverter(ApiError.class, new Annotation[0]); try { ApiError error = responseBodyObjectConverter.convert(body); if (error != null) { errorMessage = error.getMessage(); } } catch (IOException e1) { e1.printStackTrace(); } } return errorMessage; }
/** * Fetches the GoPro camera state. First, we assume that the camera is on. * Then, if we get a GONE error response, we try to the camera off request. */ public static Observable<byte[]> fetchCameraState(GoProApi goProApi) { return goProApi.fetchCameraStateWhileOn() .map(new CameraStateMapper(false)) .onErrorResumeNext(throwable -> { if (throwable instanceof HttpException) { HttpException exception = (HttpException) throwable; if (exception.code() == HTTP_GONE) { return Observable.just(GoProState.CAMERA_OFF.rawState()); // return goProApi.fetchCameraStateWhileOff() // .map(new CameraStateMapper(false)); } } return Observable.error(throwable); }); }
@SuppressWarnings("unused") @OnCheckedChanged(R.id.notificationSwitch) public void onNotificationToggled(boolean isChecked) { updatePowerToggle(isChecked, ANIMATE); if (isChecked) { goProApi.powerOn() .onErrorResumeNext(throwable -> throwable instanceof HttpException && ((HttpException) throwable).code() == 403 ? Observable.empty() : Observable.error(throwable)) .compose(RxUtils.applyApiRequestSchedulers()) .subscribe( it -> Timber.d("success"), e -> showSnackbar(newSnackbar("Failed to turn on GoPro"))); // TODO: init default mode } else { goProApi.powerOff() .onErrorResumeNext(throwable -> throwable instanceof HttpException && ((HttpException) throwable).code() == 403 ? Observable.empty() : Observable.error(throwable)) .compose(RxUtils.applyApiRequestSchedulers()) .subscribe( it -> Timber.d("success"), e -> showSnackbar(newSnackbar("Failed to turn off GoPro"))); } }