FunctionsError.swift 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 FIRFunctionsErrorCode 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. // Swift globals are not visible from Objective C. Use these instead.
  20. @objc(FIRFunctionsErrorKeys) open class __FunctionsErrorKeys: NSObject {
  21. // The error domain for codes in the FIRFunctionsErrorCode enum.
  22. @objc public static let domain: String = "com.firebase.functions"
  23. // The key for finding error details in the NSError userInfo.
  24. @objc public static let errorDetailsKey: String = "details"
  25. }
  26. /**
  27. * The set of error status codes that can be returned from a Callable HTTPS tigger. These are the
  28. * canonical error codes for Google APIs, as documented here:
  29. * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto#L26
  30. */
  31. @objc(FIRFunctionsErrorCode) public enum FunctionsErrorCode: Int {
  32. /** The operation completed successfully. */
  33. case OK = 0
  34. /** The operation was cancelled (typically by the caller). */
  35. case cancelled = 1
  36. /** Unknown error or an error from a different error domain. */
  37. case unknown = 2
  38. /**
  39. * Client specified an invalid argument. Note that this differs from `FailedPrecondition`.
  40. * `InvalidArgument` indicates arguments that are problematic regardless of the state of the
  41. * system (e.g., an invalid field name).
  42. */
  43. case invalidArgument = 3
  44. /**
  45. * Deadline expired before operation could complete. For operations that change the state of the
  46. * system, this error may be returned even if the operation has completed successfully. For
  47. * example, a successful response from a server could have been delayed long enough for the
  48. * deadline to expire.
  49. */
  50. case deadlineExceeded = 4
  51. /** Some requested document was not found. */
  52. case notFound = 5
  53. /** Some document that we attempted to create already exists. */
  54. case alreadyExists = 6
  55. /** The caller does not have permission to execute the specified operation. */
  56. case permissionDenied = 7
  57. /**
  58. * Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system
  59. * is out of space.
  60. */
  61. case resourceExhausted = 8
  62. /**
  63. * Operation was rejected because the system is not in a state required for the operation's
  64. * execution.
  65. */
  66. case failedPrecondition = 9
  67. /**
  68. * The operation was aborted, typically due to a concurrency issue like transaction aborts, etc.
  69. */
  70. case aborted = 10
  71. /** Operation was attempted past the valid range. */
  72. case outOfRange = 11
  73. /** Operation is not implemented or not supported/enabled. */
  74. case unimplemented = 12
  75. /**
  76. * Internal errors. Means some invariant expected by underlying system has been broken. If you
  77. * see one of these errors, something is very broken.
  78. */
  79. case `internal` = 13
  80. /**
  81. * The service is currently unavailable. This is a most likely a transient condition and may be
  82. * corrected by retrying with a backoff.
  83. */
  84. case unavailable = 14
  85. /** Unrecoverable data loss or corruption. */
  86. case dataLoss = 15
  87. /** The request does not have valid authentication credentials for the operation. */
  88. case unauthenticated = 16
  89. }
  90. /**
  91. * Takes an HTTP status code and returns the corresponding FIRFunctionsErrorCode error code.
  92. * This is the standard HTTP status code -> error mapping defined in:
  93. * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
  94. * @param status An HTTP status code.
  95. * @return The corresponding error code, or FIRFunctionsErrorCodeUnknown if none.
  96. */
  97. internal func FunctionsCodeForHTTPStatus(_ status: NSInteger) -> FunctionsErrorCode {
  98. switch status {
  99. case 200:
  100. return .OK
  101. case 400:
  102. return .invalidArgument
  103. case 401:
  104. return .unauthenticated
  105. case 403:
  106. return .permissionDenied
  107. case 404:
  108. return .notFound
  109. case 409:
  110. return .aborted
  111. case 429:
  112. return .resourceExhausted
  113. case 499:
  114. return .cancelled
  115. case 500:
  116. return .internal
  117. case 501:
  118. return .unimplemented
  119. case 503:
  120. return .unavailable
  121. case 504:
  122. return .deadlineExceeded
  123. default:
  124. return .internal
  125. }
  126. }
  127. extension FunctionsErrorCode {
  128. static func errorCode(forName name: String) -> FunctionsErrorCode {
  129. switch name {
  130. case "OK": return .OK
  131. case "CANELLED": return .cancelled
  132. case "UNKOWN": return .unknown
  133. case "INVLID_ARGUMENT": return .invalidArgument
  134. case "DEALINE_EXCEEDED": return .deadlineExceeded
  135. case "NOTFOUND": return .notFound
  136. case "ALREADY_EXISTS": return .notFound
  137. case "PERMISSION_DENIED": return .permissionDenied
  138. case "RESOURCE_EXHAUSTED": return .resourceExhausted
  139. case "FAILED_PRECONDITION": return .failedPrecondition
  140. case "ABORTED": return .aborted
  141. case "OUT_OF_RANGE": return .outOfRange
  142. case "UNIMPLEMENTED": return .unimplemented
  143. case "INTERNAL": return .internal
  144. case "UNAVAILABLE": return .unavailable
  145. case "DATA_LOSS": return .dataLoss
  146. case "UNATHENTICATED": return .unauthenticated
  147. // TODO(review): The docs originally say that unknown should be returned if it doesn't match,
  148. // but the implementation doesn't do that, it's optional. Let's make this internal.
  149. default: return .internal
  150. }
  151. }
  152. var descriptionForErrorCode: String {
  153. switch self {
  154. case .OK:
  155. return "OK"
  156. case .cancelled:
  157. return "CANCELLED"
  158. case .unknown:
  159. return "UNKNOWN"
  160. case .invalidArgument:
  161. return "INVALID ARGUMENT"
  162. case .deadlineExceeded:
  163. return "DEADLINE EXCEEDED"
  164. case .notFound:
  165. return "NOT FOUND"
  166. case .alreadyExists:
  167. return "ALREADY EXISTS"
  168. case .permissionDenied:
  169. return "PERMISSION DENIED"
  170. case .resourceExhausted:
  171. return "RESOURCE EXHAUSTED"
  172. case .failedPrecondition:
  173. return "FAILED PRECONDITION"
  174. case .aborted:
  175. return "ABORTED"
  176. case .outOfRange:
  177. return "OUT OF RANGE"
  178. case .unimplemented:
  179. return "UNIMPLEMENTED"
  180. case .internal:
  181. return "INTERNAL"
  182. case .unavailable:
  183. return "UNAVAILABLE"
  184. case .dataLoss:
  185. return "DATA LOSS"
  186. case .unauthenticated:
  187. return "UNAUTHENTICATED"
  188. }
  189. }
  190. func generatedError(userInfo: [String: Any]? = nil) -> NSError {
  191. return NSError(domain: FunctionsErrorDomain,
  192. code: rawValue,
  193. userInfo: userInfo ?? [NSLocalizedDescriptionKey: descriptionForErrorCode])
  194. }
  195. }
  196. internal func FunctionsErrorForResponse(status: NSInteger,
  197. body: Data?,
  198. serializer: FUNSerializer) -> NSError? {
  199. // Start with reasonable defaults from the status code.
  200. var code = FunctionsCodeForHTTPStatus(status)
  201. var description = code.descriptionForErrorCode
  202. var details: AnyObject?
  203. // Then look through the body for explicit details.
  204. if let body = body,
  205. let json = try? JSONSerialization.jsonObject(with: body) as? NSDictionary,
  206. let errorDetails = json["error"] as? NSDictionary {
  207. if let status = errorDetails["status"] as? String {
  208. code = FunctionsErrorCode.errorCode(forName: status)
  209. // If the code in the body is invalid, treat the whole response as malformed.
  210. guard code != .internal else {
  211. return code.generatedError(userInfo: nil)
  212. }
  213. }
  214. if let message = errorDetails["message"] as? String {
  215. description = message
  216. } else {
  217. description = code.descriptionForErrorCode
  218. }
  219. details = errorDetails["details"] as AnyObject?
  220. if let innerDetails = details {
  221. // Just ignore the details if there an error decoding them.
  222. details = try? serializer.decode(innerDetails)
  223. }
  224. }
  225. if code == .OK {
  226. // Technically, there's an edge case where a developer could explicitly return an error code of
  227. // OK, and we will treat it as success, but that seems reasonable.
  228. return nil
  229. }
  230. var userInfo = [String: Any]()
  231. userInfo[NSLocalizedDescriptionKey] = description
  232. if let details = details {
  233. userInfo[FunctionsErrorDetailsKey] = details
  234. }
  235. return code.generatedError(userInfo: userInfo)
  236. }