Result+Catching.swift 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. extension Result {
  17. /// Like `Result(catching:)`, but `async`.
  18. ///
  19. /// - Parameter body: An `async` closure to catch the result of.
  20. @inlinable
  21. @available(gRPCSwift 2.0, *)
  22. init(catching body: () async throws(Failure) -> 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. @available(gRPCSwift 2.0, *)
  38. func castError<NewError: Error>(
  39. to errorType: NewError.Type = NewError.self,
  40. or buildError: (any Error) -> NewError
  41. ) -> Result<Success, NewError> {
  42. return self.mapError { error in
  43. return (error as? NewError) ?? buildError(error)
  44. }
  45. }
  46. }