FunctionsError.swift 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. /**
  84. * Takes an HTTP status code and returns the corresponding `FIRFunctionsErrorCode` error code.
  85. * This is the standard HTTP status code -> error mapping defined in:
  86. * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
  87. * - Parameter status An HTTP status code.
  88. * - Returns: The corresponding error code, or `FIRFunctionsErrorCodeUnknown` if none.
  89. */
  90. func FunctionsCodeForHTTPStatus(_ status: NSInteger) -> FunctionsErrorCode {
  91. switch status {
  92. case 200:
  93. return .OK
  94. case 400:
  95. return .invalidArgument
  96. case 401:
  97. return .unauthenticated
  98. case 403:
  99. return .permissionDenied
  100. case 404:
  101. return .notFound
  102. case 409:
  103. return .alreadyExists
  104. case 429:
  105. return .resourceExhausted
  106. case 499:
  107. return .cancelled
  108. case 500:
  109. return .internal
  110. case 501:
  111. return .unimplemented
  112. case 503:
  113. return .unavailable
  114. case 504:
  115. return .deadlineExceeded
  116. default:
  117. return .internal
  118. }
  119. }
  120. extension FunctionsErrorCode {
  121. static func errorCode(forName name: String) -> FunctionsErrorCode {
  122. switch name {
  123. case "OK": return .OK
  124. case "CANCELLED": return .cancelled
  125. case "UNKNOWN": return .unknown
  126. case "INVALID_ARGUMENT": return .invalidArgument
  127. case "DEADLINE_EXCEEDED": return .deadlineExceeded
  128. case "NOT_FOUND": return .notFound
  129. case "ALREADY_EXISTS": return .alreadyExists
  130. case "PERMISSION_DENIED": return .permissionDenied
  131. case "RESOURCE_EXHAUSTED": return .resourceExhausted
  132. case "FAILED_PRECONDITION": return .failedPrecondition
  133. case "ABORTED": return .aborted
  134. case "OUT_OF_RANGE": return .outOfRange
  135. case "UNIMPLEMENTED": return .unimplemented
  136. case "INTERNAL": return .internal
  137. case "UNAVAILABLE": return .unavailable
  138. case "DATA_LOSS": return .dataLoss
  139. case "UNAUTHENTICATED": return .unauthenticated
  140. default: return .internal
  141. }
  142. }
  143. var descriptionForErrorCode: String {
  144. switch self {
  145. case .OK:
  146. return "OK"
  147. case .cancelled:
  148. return "CANCELLED"
  149. case .unknown:
  150. return "UNKNOWN"
  151. case .invalidArgument:
  152. return "INVALID ARGUMENT"
  153. case .deadlineExceeded:
  154. return "DEADLINE EXCEEDED"
  155. case .notFound:
  156. return "NOT FOUND"
  157. case .alreadyExists:
  158. return "ALREADY EXISTS"
  159. case .permissionDenied:
  160. return "PERMISSION DENIED"
  161. case .resourceExhausted:
  162. return "RESOURCE EXHAUSTED"
  163. case .failedPrecondition:
  164. return "FAILED PRECONDITION"
  165. case .aborted:
  166. return "ABORTED"
  167. case .outOfRange:
  168. return "OUT OF RANGE"
  169. case .unimplemented:
  170. return "UNIMPLEMENTED"
  171. case .internal:
  172. return "INTERNAL"
  173. case .unavailable:
  174. return "UNAVAILABLE"
  175. case .dataLoss:
  176. return "DATA LOSS"
  177. case .unauthenticated:
  178. return "UNAUTHENTICATED"
  179. }
  180. }
  181. func generatedError(userInfo: [String: Any]? = nil) -> NSError {
  182. return NSError(domain: FunctionsErrorDomain,
  183. code: rawValue,
  184. userInfo: userInfo ?? [NSLocalizedDescriptionKey: descriptionForErrorCode])
  185. }
  186. }
  187. func FunctionsErrorForResponse(status: NSInteger,
  188. body: Data?,
  189. serializer: FunctionsSerializer) -> NSError? {
  190. // Start with reasonable defaults from the status code.
  191. var code = FunctionsCodeForHTTPStatus(status)
  192. var description = code.descriptionForErrorCode
  193. var details: AnyObject?
  194. // Then look through the body for explicit details.
  195. if let body,
  196. let json = try? JSONSerialization.jsonObject(with: body) as? NSDictionary,
  197. let errorDetails = json["error"] as? NSDictionary {
  198. if let status = errorDetails["status"] as? String {
  199. code = FunctionsErrorCode.errorCode(forName: status)
  200. // If the code in the body is invalid, treat the whole response as malformed.
  201. guard code != .internal else {
  202. return code.generatedError(userInfo: nil)
  203. }
  204. }
  205. if let message = errorDetails["message"] as? String {
  206. description = message
  207. } else {
  208. description = code.descriptionForErrorCode
  209. }
  210. details = errorDetails["details"] as AnyObject?
  211. if let innerDetails = details {
  212. // Just ignore the details if there an error decoding them.
  213. details = try? serializer.decode(innerDetails)
  214. }
  215. }
  216. if code == .OK {
  217. // Technically, there's an edge case where a developer could explicitly return an error code of
  218. // OK, and we will treat it as success, but that seems reasonable.
  219. return nil
  220. }
  221. var userInfo = [String: Any]()
  222. userInfo[NSLocalizedDescriptionKey] = description
  223. if let details {
  224. userInfo[FunctionsErrorDetailsKey] = details
  225. }
  226. return code.generatedError(userInfo: userInfo)
  227. }