2016-12-29 7 views
5

Как мы можем обрабатывать различные сетевые ошибки в Rxjava2?Ошибка сетевой работы в Rxjava 2 - Модернизация 2

Мы использовали, чтобы проверить экземпляр 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); 

ссылка: 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); 
});