Combine操作符Error示例


2天前 4次点击 来自 移动端

标签: Swift

Error Handing 错误处理

如何处理pipline中的错误

catch/tryCatch

enum MyError: Error {
    case custom
}

let publisher = PassthroughSubject<String, Error>()

publisher
    .catch { _ in
        Just(":END")
    }
    .sink(receiveCompletion: { completion in
        print(completion)
    }, receiveValue: { value in
        print(value)
    })

publisher.send("1")
publisher.send("2")
publisher.send(completion: Subscribers.Completion.failure(MyError.custom))
publisher.send("3")

assertNoFailure

主要用于test,略

retry

当上游的publisher发送了错误后,retry重新对publisher进行订阅,如用于某个网络请求进行重试操作

func loadData() {
    let myURL = URL(string: "https://www.example.com")

    URLSession.shared.dataTaskPublisher(for: myURL!)
        .retry(3)
        .map({ (page) -> WebSiteData in
            return WebSiteData(rawHTML: String(decoding: page.data, as: UTF8.self))
        })
        .catch { error in
            return Just(WebSiteData(rawHTML: "<HTML>Unable to load page - timed out.</HTML>"))
        }
        .assign(to: \.data, on: self)
        .store(in: &cancellables)
}

mapError

将其他Error转换成自定义Error

.mapError { error -> ChangingErrorTests.APIError in
    // if it's our kind of error already, we can return it directly
    if let error = error as? APIError {
        return error
    }
    // if it is a URLError, we can convert it into our more general error kind
    if let urlerror = error as? URLError {
        return APIError.networkError(from: urlerror)
    }
    // if all else fails, return the unknown error condition
    return APIError.unknown
}

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1