Network Error Handling in Rxjava 2 - Retrofit 2

How can we handle various network errors in Rxjava2?

We used throwable instance validation if it is an IOException or HttpException again with Rxjava 1, however in RxJava 2 the throwing error is of type GaiException .

code snippet

RestAPI restAPI = RetrofitHelper.createRetrofitWithGson().create(RestAPI.class); Observable<BaseResponseTourPhoto> observable = restAPI.fetchData("Bearer " + getAccessToken(), "2", "" + page) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); Disposable subscription = observable.subscribe(BaseResponse-> { onLoadingFinish(isPageLoading, isRefreshing); onLoadingSuccess(isPageLoading, BaseResponse); writeToRealm(BaseResponse.getData()); }, error -> { onLoadingFinish(isPageLoading, isRefreshing); onLoadingFailed(error); }); mCompositeDisposable = new CompositeDisposable(); mCompositeDisposable.add(subscription); unsubscribeOnDestroy(mCompositeDisposable); 

link: https://github.com/square/retrofit/issues/690 https://android.googlesource.com/platform/libcore/+/5d930ca/luni/src/main/java/android/system/GaiException.java

+5
source share
1 answer

Add onErrorReturn () to the chain

 .onErrorReturn((Throwable ex) -> { print(ex); //examine error here return ""; //empty object of the datatype }) .subscribe((String res) -> { if(res.isEmpty()) //some condition to check error return; doStuff(res); }); 
+8
source

Source: https://habr.com/ru/post/1262028/


All Articles