RPCError.swift 11 KB

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