2
0

Result+Catching.swift 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*
  2. * Copyright 2023, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  17. extension Result where Failure == any Error {
  18. /// Like `Result(catching:)`, but `async`.
  19. ///
  20. /// - Parameter body: An `async` closure to catch the result of.
  21. @inlinable
  22. init(catching body: () async throws -> Success) async {
  23. do {
  24. self = .success(try await body())
  25. } catch {
  26. self = .failure(error)
  27. }
  28. }
  29. /// Attempts to map the error to the given error type.
  30. ///
  31. /// If the cast fails then the provided closure is used to create an error of the given type.
  32. ///
  33. /// - Parameters:
  34. /// - errorType: The type of error to cast to.
  35. /// - buildError: A closure which constructs the desired error if the cast fails.
  36. @inlinable
  37. func castError<NewError: Error>(
  38. to errorType: NewError.Type = NewError.self,
  39. or buildError: (any Error) -> NewError
  40. ) -> Result<Success, NewError> {
  41. return self.mapError { error in
  42. return (error as? NewError) ?? buildError(error)
  43. }
  44. }
  45. }