FunctionsError.swift 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. // Copyright 2022 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. /// The error domain for codes in the ``FunctionsErrorCode`` enum.
  16. public let FunctionsErrorDomain: String = "com.firebase.functions"
  17. /// The key for finding error details in the `NSError` userInfo.
  18. public let FunctionsErrorDetailsKey: String = "details"
  19. /**
  20. * The set of error status codes that can be returned from a Callable HTTPS trigger. These are the
  21. * canonical error codes for Google APIs, as documented here:
  22. * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto#L26
  23. */
  24. @objc(FIRFunctionsErrorCode) public enum FunctionsErrorCode: Int {
  25. /** The operation completed successfully. */
  26. case OK = 0
  27. /** The operation was cancelled (typically by the caller). */
  28. case cancelled = 1
  29. /** Unknown error or an error from a different error domain. */
  30. case unknown = 2
  31. /**
  32. * Client specified an invalid argument. Note that this differs from `FailedPrecondition`.
  33. * `InvalidArgument` indicates arguments that are problematic regardless of the state of the
  34. * system (e.g., an invalid field name).
  35. */
  36. case invalidArgument = 3
  37. /**
  38. * Deadline expired before operation could complete. For operations that change the state of the
  39. * system, this error may be returned even if the operation has completed successfully. For
  40. * example, a successful response from a server could have been delayed long enough for the
  41. * deadline to expire.
  42. */
  43. case deadlineExceeded = 4
  44. /** Some requested document was not found. */
  45. case notFound = 5
  46. /** Some document that we attempted to create already exists. */
  47. case alreadyExists = 6
  48. /** The caller does not have permission to execute the specified operation. */
  49. case permissionDenied = 7
  50. /**
  51. * Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system
  52. * is out of space.
  53. */
  54. case resourceExhausted = 8
  55. /**
  56. * Operation was rejected because the system is not in a state required for the operation's
  57. * execution.
  58. */
  59. case failedPrecondition = 9
  60. /**
  61. * The operation was aborted, typically due to a concurrency issue like transaction aborts, etc.
  62. */
  63. case aborted = 10
  64. /** Operation was attempted past the valid range. */
  65. case outOfRange = 11
  66. /** Operation is not implemented or not supported/enabled. */
  67. case unimplemented = 12
  68. /**
  69. * Internal errors. Means some invariant expected by underlying system has been broken. If you
  70. * see one of these errors, something is very broken.
  71. */
  72. case `internal` = 13
  73. /**
  74. * The service is currently unavailable. This is a most likely a transient condition and may be
  75. * corrected by retrying with a backoff.
  76. */
  77. case unavailable = 14
  78. /** Unrecoverable data loss or corruption. */
  79. case dataLoss = 15
  80. /** The request does not have valid authentication credentials for the operation. */
  81. case unauthenticated = 16
  82. }
  83. private extension FunctionsErrorCode {
  84. /// Takes an HTTP status code and returns the corresponding `FIRFunctionsErrorCode` error code.
  85. ///
  86. /// + This is the standard HTTP status code -> error mapping defined in:
  87. /// https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
  88. ///
  89. /// - Parameter httpStatusCode: An HTTP status code.
  90. /// - Returns: A `FunctionsErrorCode`. Falls back to `internal` for unknown status codes.
  91. init(httpStatusCode: Int) {
  92. self = switch httpStatusCode {
  93. case 200: .OK
  94. case 400: .invalidArgument
  95. case 401: .unauthenticated
  96. case 403: .permissionDenied
  97. case 404: .notFound
  98. case 409: .alreadyExists
  99. case 429: .resourceExhausted
  100. case 499: .cancelled
  101. case 500: .internal
  102. case 501: .unimplemented
  103. case 503: .unavailable
  104. case 504: .deadlineExceeded
  105. default: .internal
  106. }
  107. }
  108. init(errorName: String) {
  109. self = switch errorName {
  110. case "OK": .OK
  111. case "CANCELLED": .cancelled
  112. case "UNKNOWN": .unknown
  113. case "INVALID_ARGUMENT": .invalidArgument
  114. case "DEADLINE_EXCEEDED": .deadlineExceeded
  115. case "NOT_FOUND": .notFound
  116. case "ALREADY_EXISTS": .alreadyExists
  117. case "PERMISSION_DENIED": .permissionDenied
  118. case "RESOURCE_EXHAUSTED": .resourceExhausted
  119. case "FAILED_PRECONDITION": .failedPrecondition
  120. case "ABORTED": .aborted
  121. case "OUT_OF_RANGE": .outOfRange
  122. case "UNIMPLEMENTED": .unimplemented
  123. case "INTERNAL": .internal
  124. case "UNAVAILABLE": .unavailable
  125. case "DATA_LOSS": .dataLoss
  126. case "UNAUTHENTICATED": .unauthenticated
  127. default: .internal
  128. }
  129. }
  130. }
  131. /// The object used to report errors that occur during a function’s execution.
  132. struct FunctionsError: CustomNSError {
  133. static let errorDomain = FunctionsErrorDomain
  134. let code: FunctionsErrorCode
  135. let errorUserInfo: [String: Any]
  136. var errorCode: FunctionsErrorCode.RawValue { code.rawValue }
  137. init(_ code: FunctionsErrorCode, userInfo: [String: Any]? = nil) {
  138. self.code = code
  139. errorUserInfo = userInfo ?? [NSLocalizedDescriptionKey: Self.errorDescription(from: code)]
  140. }
  141. /// Initializes a `FunctionsError` from the HTTP status code and response body.
  142. ///
  143. /// - Parameters:
  144. /// - httpStatusCode: The HTTP status code reported during a function’s execution. Only a subset
  145. /// of codes are supported.
  146. /// - body: The optional response data which may contain information about the error. The
  147. /// following schema is expected:
  148. /// ```
  149. /// {
  150. /// "error": {
  151. /// "status": "PERMISSION_DENIED",
  152. /// "message": "You are not allowed to perform this operation",
  153. /// "details": 123 // Any value supported by `FunctionsSerializer`
  154. /// }
  155. /// ```
  156. /// - serializer: The `FunctionsSerializer` used to decode `details` in the error body.
  157. init?(httpStatusCode: Int, region: String, url: URL, body: Data?,
  158. serializer: FunctionsSerializer) {
  159. // Start with reasonable defaults from the status code.
  160. var code = FunctionsErrorCode(httpStatusCode: httpStatusCode)
  161. var description = Self.errorDescription(from: code)
  162. var details: Any?
  163. // Then look through the body for explicit details.
  164. if let body,
  165. let json = try? JSONSerialization.jsonObject(with: body) as? [String: Any],
  166. let errorDetails = json["error"] as? [String: Any] {
  167. if let status = errorDetails["status"] as? String {
  168. code = FunctionsErrorCode(errorName: status)
  169. // If the code in the body is invalid, treat the whole response as malformed.
  170. guard code != .internal else {
  171. self.init(code)
  172. return
  173. }
  174. }
  175. if let message = errorDetails["message"] as? String {
  176. description = message
  177. } else {
  178. description = Self.errorDescription(from: code)
  179. }
  180. details = errorDetails["details"] as Any?
  181. // Update `details` only if decoding succeeds;
  182. // otherwise, keep the original object.
  183. if let innerDetails = details,
  184. let decodedDetails = try? serializer.decode(innerDetails) {
  185. details = decodedDetails
  186. }
  187. }
  188. if code == .OK {
  189. // Technically, there's an edge case where a developer could explicitly return an error code
  190. // of
  191. // OK, and we will treat it as success, but that seems reasonable.
  192. return nil
  193. }
  194. var userInfo = [String: Any]()
  195. userInfo[NSLocalizedDescriptionKey] = description
  196. userInfo["region"] = region
  197. userInfo["url"] = url
  198. if let details {
  199. userInfo[FunctionsErrorDetailsKey] = details
  200. }
  201. self.init(code, userInfo: userInfo)
  202. }
  203. private static func errorDescription(from code: FunctionsErrorCode) -> String {
  204. switch code {
  205. case .OK: "OK"
  206. case .cancelled: "CANCELLED"
  207. case .unknown: "UNKNOWN"
  208. case .invalidArgument: "INVALID ARGUMENT"
  209. case .deadlineExceeded: "DEADLINE EXCEEDED"
  210. case .notFound: "NOT FOUND"
  211. case .alreadyExists: "ALREADY EXISTS"
  212. case .permissionDenied: "PERMISSION DENIED"
  213. case .resourceExhausted: "RESOURCE EXHAUSTED"
  214. case .failedPrecondition: "FAILED PRECONDITION"
  215. case .aborted: "ABORTED"
  216. case .outOfRange: "OUT OF RANGE"
  217. case .unimplemented: "UNIMPLEMENTED"
  218. case .internal: "INTERNAL"
  219. case .unavailable: "UNAVAILABLE"
  220. case .dataLoss: "DATA LOSS"
  221. case .unauthenticated: "UNAUTHENTICATED"
  222. }
  223. }
  224. }