我们如何处理 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
最佳答案
添加 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);
});
关于rx-java - 处理 Rxjava 2 中的网络错误 - Retrofit 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41379815/