Result+Catching.swift 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. init(catching body: () async throws(Failure) -> Success) async {
  22. do {
  23. self = .success(try await body())
  24. } catch {
  25. self = .failure(error)
  26. }
  27. }
  28. /// Attempts to map the error to the given error type.
  29. ///
  30. /// If the cast fails then the provided closure is used to create an error of the given type.
  31. ///
  32. /// - Parameters:
  33. /// - errorType: The type of error to cast to.
  34. /// - buildError: A closure which constructs the desired error if the cast fails.
  35. @inlinable
  36. func castError<NewError: Error>(
  37. to errorType: NewError.Type = NewError.self,
  38. or buildError: (any Error) -> NewError
  39. ) -> Result<Success, NewError> {
  40. return self.mapError { error in
  41. return (error as? NewError) ?? buildError(error)
  42. }
  43. }
  44. }