Handling Network Error in Rxjava 2 - Retrofit 2

10.1k views Asked by At

How can we handle different network errors in Rxjava2 ?

We used to check the instance of the throwable if it's of IOException or HttpException back with Rxjava 1 ,however, in RxJava 2 the throwable 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);

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

1

There are 1 answers

0
Ekim Kano On

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);
});