實例方法
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(_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。