一般情況下,RxJava產(chǎn)生的一切異常,都會傳遞至onError進(jìn)行處理。但在有些情況下,我們需要在onError之前捕獲這些異常并作相應(yīng)的處理,此時就用到了RxJava的Error Handling系列操作符。
RxJava的Error Handing系列操作符有3個:
- onErrorReturn
- onErrorResumeNext
- onExceptionResumeNext
onErrorReturn(Func1)

The onErrorReturn method returns an Observable that mirrors the behavior of the source Observable, unless that Observable invokes onError in which case, rather than propagating that error to the observer, onErrorReturn will instead emit a specified item and invoke the observer’s onCompleted method.
以上為doc說明,說白了就是該操作符會攔截(攔截指的是不會觸發(fā)onError,下同)發(fā)送給觀察者的異常,并發(fā)送出一個正常的item,這個item需要我們自己在Func1中自定義。
.onErrorReturn(new Func1<Throwable, Object>() {
@Override
public Object call(Throwable throwable) {
// TODO: handle throwable then return specified object
return null;
}
})
onErrorResumeNext(Func1)
onErrorResumeNext(Observable)

The onErrorResumeNext method returns an Observable that mirrors the behavior of the source Observable, unless that Observable invokes onError in which case, rather than propagating that error to the observer, onErrorResumeNext will instead begin mirroring a second, backup Observable.
同樣是產(chǎn)生源Observable的鏡像,攔截異常,并向事件流發(fā)射一個Observable,可直接傳入一個Observable對象,或由Func1生成。
onExceptionResumeNext(Observable)

Much like onErrorResumeNext method, this returns an Observable that mirrors the behavior of the source Observable, unless that Observable invokes onError in which case, if the Throwable passed to onError is an Exception, rather than propagating that Exception to the observer, onExceptionResumeNext will instead begin mirroring a second, backup Observable. If the Throwable is not an Exception, the Observable returned by onExceptionResumeNext will propagate it to its observer’s onError method and will not invoke its backup Observable.
和onErrorResumeNext很像,只不過此操作符攔截的是Exception,并且參數(shù)只能是Observable對象。需注意的是,如果產(chǎn)生的Throwable不是Exception,會被發(fā)送至由onExceptionResumeNext返回的Observable所注冊的Observer中,而不會調(diào)用backup Observable(這個backup是指的什么,源Obervable嗎?)。
doOnError(Action1)
這個操作符并不在官方文檔的Error Handling系列中,而屬于Do系列,和Error Handling系列不同,doOnError并不會攔截異常,只是通過Action1回掉傳入Thorwable,該Throwable還是會發(fā)送至onError。
之所以放在這里一起說,是因為我在開發(fā)時需要在返回未登陸異常的時候,清除一下本地的UserCache,異常還是需要被正常發(fā)送給觀察者。最開始還用onErrorReturn去處理,完成后再手動拋出一個RuntimeException,結(jié)果導(dǎo)致產(chǎn)生其他Exception或Throwable時不能得到正確處理,真是傻透了。