8

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

我们曾经使用 Rxjava 1 检查 throwable 的实例,如果它是 IOException 或 HttpException 返回,但是在 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);

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

4

1 回答 1

10

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);
});
于 2017-03-10T11:14:52.017 回答