处理Rxjava 2中的网络错误 - 改造2

时间:2016-12-29 12:32:41

标签: rx-java retrofit2 okhttp okhttp3 rx-java2

我们如何处理Rxjava2中的不同网络错误?

我们曾经检查过throwable的实例,如果它是IOException或HttpException返回Rxjava 1,但是,在RxJava 2中,throwable错误的类型为 GaiException

代码段

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

参考:overload resolution https://github.com/square/retrofit/issues/690

1 个答案:

答案 0 :(得分:9)

onErrorReturn()添加到链

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