RPCError.swift 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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. /// An error representing the outcome of an RPC.
  17. ///
  18. /// See also ``Status``.
  19. public struct RPCError: Sendable, Hashable, Error {
  20. /// A code representing the high-level domain of the error.
  21. public var code: Code
  22. /// A message providing additional context about the error.
  23. public var message: String
  24. /// Metadata associated with the error.
  25. ///
  26. /// Any metadata included in the error thrown from a service will be sent back to the client and
  27. /// conversely any ``RPCError`` received by the client may include metadata sent by a service.
  28. ///
  29. /// Note that clients and servers may synthesise errors which may not include metadata.
  30. public var metadata: Metadata
  31. /// The original error which led to this error being thrown.
  32. public var cause: (any Error)?
  33. /// Create a new RPC error.
  34. ///
  35. /// - Parameters:
  36. /// - code: The status code.
  37. /// - message: A message providing additional context about the code.
  38. /// - metadata: Any metadata to attach to the error.
  39. /// - cause: An underlying error which led to this error being thrown.
  40. public init(code: Code, message: String, metadata: Metadata = [:], cause: (any Error)? = nil) {
  41. self.code = code
  42. self.message = message
  43. self.metadata = metadata
  44. self.cause = cause
  45. }
  46. /// Create a new RPC error from the provided ``Status``.
  47. ///
  48. /// Returns `nil` if the provided ``Status`` has code ``Status/Code-swift.struct/ok``.
  49. ///
  50. /// - Parameters:
  51. /// - status: The status to convert.
  52. /// - metadata: Any metadata to attach to the error.
  53. public init?(status: Status, metadata: Metadata = [:]) {
  54. guard let code = Code(status.code) else { return nil }
  55. self.init(code: code, message: status.message, metadata: metadata)
  56. }
  57. public func hash(into hasher: inout Hasher) {
  58. hasher.combine(self.code)
  59. hasher.combine(self.message)
  60. hasher.combine(self.metadata)
  61. }
  62. public static func == (lhs: RPCError, rhs: RPCError) -> Bool {
  63. return lhs.code == rhs.code && lhs.message == rhs.message && lhs.metadata == rhs.metadata
  64. }
  65. }
  66. extension RPCError: CustomStringConvertible {
  67. public var description: String {
  68. if let cause = self.cause {
  69. return "\(self.code): \"\(self.message)\" (cause: \"\(cause)\")"
  70. } else {
  71. return "\(self.code): \"\(self.message)\""
  72. }
  73. }
  74. }
  75. extension RPCError {
  76. public struct Code: Hashable, Sendable, CustomStringConvertible {
  77. /// The numeric value of the error code.
  78. public var rawValue: Int { Int(self.wrapped.rawValue) }
  79. internal var wrapped: Status.Code.Wrapped
  80. private init(code: Status.Code.Wrapped) {
  81. self.wrapped = code
  82. }
  83. /// Creates an error code from the given ``Status/Code-swift.struct``; returns `nil` if the
  84. /// code is ``Status/Code-swift.struct/ok``.
  85. ///
  86. /// - Parameter code: The status code to create this ``RPCError/Code-swift.struct`` from.
  87. public init?(_ code: Status.Code) {
  88. if code == .ok {
  89. return nil
  90. } else {
  91. self.wrapped = code.wrapped
  92. }
  93. }
  94. public var description: String {
  95. String(describing: self.wrapped)
  96. }
  97. }
  98. }
  99. extension RPCError.Code {
  100. /// The operation was cancelled (typically by the caller).
  101. public static let cancelled = Self(code: .cancelled)
  102. /// Unknown error. An example of where this error may be returned is if a
  103. /// Status value received from another address space belongs to an error-space
  104. /// that is not known in this address space. Also errors raised by APIs that
  105. /// do not return enough error information may be converted to this error.
  106. public static let unknown = Self(code: .unknown)
  107. /// Client specified an invalid argument. Note that this differs from
  108. /// ``failedPrecondition``. ``invalidArgument`` indicates arguments that are
  109. /// problematic regardless of the state of the system (e.g., a malformed file
  110. /// name).
  111. public static let invalidArgument = Self(code: .invalidArgument)
  112. /// Deadline expired before operation could complete. For operations that
  113. /// change the state of the system, this error may be returned even if the
  114. /// operation has completed successfully. For example, a successful response
  115. /// from a server could have been delayed long enough for the deadline to
  116. /// expire.
  117. public static let deadlineExceeded = Self(code: .deadlineExceeded)
  118. /// Some requested entity (e.g., file or directory) was not found.
  119. public static let notFound = Self(code: .notFound)
  120. /// Some entity that we attempted to create (e.g., file or directory) already
  121. /// exists.
  122. public static let alreadyExists = Self(code: .alreadyExists)
  123. /// The caller does not have permission to execute the specified operation.
  124. /// ``permissionDenied`` must not be used for rejections caused by exhausting
  125. /// some resource (use ``resourceExhausted`` instead for those errors).
  126. /// ``permissionDenied`` must not be used if the caller can not be identified
  127. /// (use ``unauthenticated`` instead for those errors).
  128. public static let permissionDenied = Self(code: .permissionDenied)
  129. /// Some resource has been exhausted, perhaps a per-user quota, or perhaps the
  130. /// entire file system is out of space.
  131. public static let resourceExhausted = Self(code: .resourceExhausted)
  132. /// Operation was rejected because the system is not in a state required for
  133. /// the operation's execution. For example, directory to be deleted may be
  134. /// non-empty, an rmdir operation is applied to a non-directory, etc.
  135. ///
  136. /// A litmus test that may help a service implementor in deciding
  137. /// between ``failedPrecondition``, ``aborted``, and ``unavailable``:
  138. /// - Use ``unavailable`` if the client can retry just the failing call.
  139. /// - Use ``aborted`` if the client should retry at a higher-level
  140. /// (e.g., restarting a read-modify-write sequence).
  141. /// - Use ``failedPrecondition`` if the client should not retry until
  142. /// the system state has been explicitly fixed. E.g., if an "rmdir"
  143. /// fails because the directory is non-empty, ``failedPrecondition``
  144. /// should be returned since the client should not retry unless
  145. /// they have first fixed up the directory by deleting files from it.
  146. /// - Use ``failedPrecondition`` if the client performs conditional
  147. /// REST Get/Update/Delete on a resource and the resource on the
  148. /// server does not match the condition. E.g., conflicting
  149. /// read-modify-write on the same resource.
  150. public static let failedPrecondition = Self(code: .failedPrecondition)
  151. /// The operation was aborted, typically due to a concurrency issue like
  152. /// sequencer check failures, transaction aborts, etc.
  153. ///
  154. /// See litmus test above for deciding between ``failedPrecondition``, ``aborted``,
  155. /// and ``unavailable``.
  156. public static let aborted = Self(code: .aborted)
  157. /// Operation was attempted past the valid range. E.g., seeking or reading
  158. /// past end of file.
  159. ///
  160. /// Unlike ``invalidArgument``, this error indicates a problem that may be fixed
  161. /// if the system state changes. For example, a 32-bit file system will
  162. /// generate ``invalidArgument`` if asked to read at an offset that is not in the
  163. /// range [0,2^32-1], but it will generate ``outOfRange`` if asked to read from
  164. /// an offset past the current file size.
  165. ///
  166. /// There is a fair bit of overlap between ``failedPrecondition`` and
  167. /// ``outOfRange``. We recommend using ``outOfRange`` (the more specific error)
  168. /// when it applies so that callers who are iterating through a space can
  169. /// easily look for an ``outOfRange`` error to detect when they are done.
  170. public static let outOfRange = Self(code: .outOfRange)
  171. /// Operation is not implemented or not supported/enabled in this service.
  172. public static let unimplemented = Self(code: .unimplemented)
  173. /// Internal errors. Means some invariants expected by underlying System has
  174. /// been broken. If you see one of these errors, Something is very broken.
  175. public static let internalError = Self(code: .internalError)
  176. /// The service is currently unavailable. This is a most likely a transient
  177. /// condition and may be corrected by retrying with a backoff.
  178. ///
  179. /// See litmus test above for deciding between ``failedPrecondition``, ``aborted``,
  180. /// and ``unavailable``.
  181. public static let unavailable = Self(code: .unavailable)
  182. /// Unrecoverable data loss or corruption.
  183. public static let dataLoss = Self(code: .dataLoss)
  184. /// The request does not have valid authentication credentials for the
  185. /// operation.
  186. public static let unauthenticated = Self(code: .unauthenticated)
  187. }