1. 程式人生 > >Error Handling Operators

Error Handling Operators

CatchError

從一個錯誤事件中恢復,將錯誤事件替換成一個備選序列

Catch.png

let sequenceThatFails = PublishSubject<String>()
let recoverySequence = PublishSubject<String>()

sequenceThatFails.catchError { (error) -> Observable<String> in
        print("error: ", error)
        return recoverySequence
    }.subscribe
(onNext: { print($0) }).disposed(by: disposeBag) sequenceThatFails.onNext("A") sequenceThatFails.onNext("B") sequenceThatFails.onNext("C") sequenceThatFails.onNext("D") sequenceThatFails.onError(HHError(name: "test")) recoverySequence.onNext("1") recoverySequence.onNext("2") /* A B C D error: __lldb_expr_144.HHError 1 2 */

CatchErrorJustReturn

會將 error 事件替換成其他的一個元素,然後結束該序列

onErrorReturn.png

sequenceThatFails.catchErrorJustReturn("666")
    .subscribe(onNext: {
    print($0)
}).disposed(by: disposeBag)

sequenceThatFails.onNext("1")
sequenceThatFails.onNext("2")
sequenceThatFails.onNext("3")
sequenceThatFails.onError(HHError(name: "test"
)) /* 666 */

Retry

如果源 Observable 產生一個錯誤事件,重新對它進行訂閱,希望它不會再次產生錯誤

retry.C.png

var count = 1
let canErrorSequence = Observable<String>.create { (observer) -> Disposable in
    observer.onNext("A")
    observer.onNext("B")
    observer.onNext("C")

    if count == 1 {
        observer.onError(HHError.init(name: "text"))
        print("Error encountered")
        count += 1
    }

    observer.onNext("1")
    observer.onNext("2")
    observer.onNext("3")
    observer.onCompleted()

    return Disposables.create()

}

canErrorSequence.retry().subscribe(onNext: {
    print($0)
}).disposed(by: disposeBag)

/*
 A
 B
 C
 Error encountered
 A
 B
 C
 1
 2
 3
 */

Debug

將 debug 除錯操作符新增到一個鏈式步驟當中,這樣系統就能將所有的訂閱者、事件、和處理等詳細資訊打印出來,方便我們開發除錯

/// debug() 不傳引數 列印當前方法名
Observable.of("A", "B", "C", "D", "E", "F", "G").debug().subscribe(onNext: {
    print($0)
}).disposed(by: disposeBag)

/// debug() 傳引數 列印引數名
Observable.of("A", "B", "C", "D", "E", "F", "G").debug("除錯:").subscribe(onNext: {
    print($0)
}).disposed(by: disposeBag)