2016-12-29 86 views
5

我們如何處理Rxjava2中的不同網絡錯誤?在Rxjava 2中處理網絡錯誤 - 改進2

我們用來檢查拋出的情況下,如果它是IOException的或HttpException回來Rxjava 1,然而,在RxJava 2拋出的錯誤是型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

+0

正在使用RxJava2CallAdapterFactory作爲適配器 – mhdtouban

回答

7

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