实例方法
try
tryCatch(_:)
通过将上游发布者替换为另一个发布者或引发新错误来处理来自上游发布者的错误。
声明
func tryCatch<P>(_ handler: @escaping (Self.Failure) throws -> P) -> Publishers.TryCatch<Self, P> where P : Publisher, Self.Output == P.Output
返回值
通过将失败的发布者替换为另一个发布者或错误来处理来自上游发布者的错误的发布者。
参数
handler
接受上游失败作为输入的抛出闭包。此闭包可以用新的发布者替换上游发布者,也可以向下游订阅者抛出新错误。
详述
使用Publisher/tryCatch(_:)
来决定如何处理来自上游发布者的问题,方法是用新的发布者替换发布者,或者抛出新的错误。
在下面的示例中,数组发布者发出 Publisher/tryMap(_:)
运算符评估的值以确保值大于零。如果值不大于零,则操作符向下游订阅者抛出错误,让其知道存在问题。订阅者 Publisher/tryCatch(_:)
将错误替换为使用 Just
的新发布者,以在流正常结束之前发布最终值。
enum SimpleError: Error { case error }
var numbers = [5, 4, 3, 2, 1, -1, 7, 8, 9, 10]
cancellable = numbers.publisher
.tryMap { v in
if v > 0 {
return v
} else {
throw SimpleError.error
}
}
.tryCatch { error in
Just(0) // Send a final value before completing normally.
// Alternatively, throw a new error to terminate the stream.
}
.sink(receiveCompletion: { print ("Completion: \($0).") },
receiveValue: { print ("Received \($0).") }
)
// Received 5.
// Received 4.
// Received 3.
// Received 2.
// Received 1.
// Received 0.
// Completion: finished.
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相关用法
- Swift Result.Publisher tryCompactMap(_:)用法及代码示例
- Swift Result.Publisher tryLast(where:)用法及代码示例
- Swift Result.Publisher tryReduce(_:_:)用法及代码示例
- Swift Result.Publisher tryFilter(_:)用法及代码示例
- Swift Result.Publisher tryFirst(where:)用法及代码示例
- Swift Result.Publisher tryPrefix(while:)用法及代码示例
- Swift Result.Publisher tryScan(_:_:)用法及代码示例
- Swift Result.Publisher tryMap(_:)用法及代码示例
- Swift Result.Publisher tryDrop(while:)用法及代码示例
- Swift Result.Publisher timeout(_:scheduler:options:customError:)用法及代码示例
- Swift Result.Publisher throttle(for:scheduler:latest:)用法及代码示例
- Swift Result.Publisher zip(_:_:_:)用法及代码示例
- Swift Result.Publisher sink(receiveCompletion:receiveValue:)用法及代码示例
- Swift Result.Publisher merge(with:_:_:)用法及代码示例
- Swift Result.Publisher print(_:to:)用法及代码示例
- Swift Result.Publisher sink(receiveValue:)用法及代码示例
- Swift Result.Publisher eraseToAnyPublisher()用法及代码示例
- Swift Result.Publisher setFailureType(to:)用法及代码示例
- Swift Result.Publisher first(where:)用法及代码示例
- Swift Result.Publisher output(at:)用法及代码示例
- Swift Result.Publisher dropFirst(_:)用法及代码示例
- Swift Result.Publisher merge(with:_:_:_:_:_:_:)用法及代码示例
- Swift Result.Publisher flatMap(maxPublishers:_:)用法及代码示例
- Swift Result.Publisher map(_:_:_:)用法及代码示例
- Swift Result.Publisher catch(_:)用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 Result.Publisher tryCatch(_:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。