RPCError.swift 13 KB

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