FunctionsError.swift 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. 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 status: An HTTP status code.
  90. /// - Returns: A `FunctionsErrorCode`. Falls back to `internal` for unknown status codes.
  91. static func errorCode(forHTTPStatus status: Int) -> Self {
  92. switch status {
  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. static func errorCode(forName name: String) -> FunctionsErrorCode {
  109. switch name {
  110. case "OK": return .OK
  111. case "CANCELLED": return .cancelled
  112. case "UNKNOWN": return .unknown
  113. case "INVALID_ARGUMENT": return .invalidArgument
  114. case "DEADLINE_EXCEEDED": return .deadlineExceeded
  115. case "NOT_FOUND": return .notFound
  116. case "ALREADY_EXISTS": return .alreadyExists
  117. case "PERMISSION_DENIED": return .permissionDenied
  118. case "RESOURCE_EXHAUSTED": return .resourceExhausted
  119. case "FAILED_PRECONDITION": return .failedPrecondition
  120. case "ABORTED": return .aborted
  121. case "OUT_OF_RANGE": return .outOfRange
  122. case "UNIMPLEMENTED": return .unimplemented
  123. case "INTERNAL": return .internal
  124. case "UNAVAILABLE": return .unavailable
  125. case "DATA_LOSS": return .dataLoss
  126. case "UNAUTHENTICATED": return .unauthenticated
  127. default: return .internal
  128. }
  129. }
  130. var descriptionForErrorCode: String {
  131. switch self {
  132. case .OK:
  133. return "OK"
  134. case .cancelled:
  135. return "CANCELLED"
  136. case .unknown:
  137. return "UNKNOWN"
  138. case .invalidArgument:
  139. return "INVALID ARGUMENT"
  140. case .deadlineExceeded:
  141. return "DEADLINE EXCEEDED"
  142. case .notFound:
  143. return "NOT FOUND"
  144. case .alreadyExists:
  145. return "ALREADY EXISTS"
  146. case .permissionDenied:
  147. return "PERMISSION DENIED"
  148. case .resourceExhausted:
  149. return "RESOURCE EXHAUSTED"
  150. case .failedPrecondition:
  151. return "FAILED PRECONDITION"
  152. case .aborted:
  153. return "ABORTED"
  154. case .outOfRange:
  155. return "OUT OF RANGE"
  156. case .unimplemented:
  157. return "UNIMPLEMENTED"
  158. case .internal:
  159. return "INTERNAL"
  160. case .unavailable:
  161. return "UNAVAILABLE"
  162. case .dataLoss:
  163. return "DATA LOSS"
  164. case .unauthenticated:
  165. return "UNAUTHENTICATED"
  166. }
  167. }
  168. func generatedError(userInfo: [String: Any]? = nil) -> NSError {
  169. return NSError(domain: FunctionsErrorDomain,
  170. code: rawValue,
  171. userInfo: userInfo ?? [NSLocalizedDescriptionKey: descriptionForErrorCode])
  172. }
  173. static func errorForResponse(status: Int,
  174. body: Data?,
  175. serializer: FunctionsSerializer) -> NSError? {
  176. // Start with reasonable defaults from the status code.
  177. var code = FunctionsErrorCode.errorCode(forHTTPStatus: status)
  178. var description = code.descriptionForErrorCode
  179. var details: AnyObject?
  180. // Then look through the body for explicit details.
  181. if let body,
  182. let json = try? JSONSerialization.jsonObject(with: body) as? NSDictionary,
  183. let errorDetails = json["error"] as? NSDictionary {
  184. if let status = errorDetails["status"] as? String {
  185. code = .errorCode(forName: status)
  186. // If the code in the body is invalid, treat the whole response as malformed.
  187. guard code != .internal else {
  188. return code.generatedError(userInfo: nil)
  189. }
  190. }
  191. if let message = errorDetails["message"] as? String {
  192. description = message
  193. } else {
  194. description = code.descriptionForErrorCode
  195. }
  196. details = errorDetails["details"] as AnyObject?
  197. // Update `details` only if decoding succeeds;
  198. // otherwise, keep the original object.
  199. if let innerDetails = details,
  200. let decodedDetails = try? serializer.decode(innerDetails) {
  201. details = decodedDetails
  202. }
  203. }
  204. if code == .OK {
  205. // Technically, there's an edge case where a developer could explicitly return an error code
  206. // of
  207. // OK, and we will treat it as success, but that seems reasonable.
  208. return nil
  209. }
  210. var userInfo = [String: Any]()
  211. userInfo[NSLocalizedDescriptionKey] = description
  212. if let details {
  213. userInfo[FunctionsErrorDetailsKey] = details
  214. }
  215. return code.generatedError(userInfo: userInfo)
  216. }
  217. }