AFError.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. //
  2. // AFError.swift
  3. //
  4. // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. /// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with
  26. /// their own associated reasons.
  27. ///
  28. /// - explicitlyCancelled: Returned when a `Request` is explicitly cancelled.
  29. /// - invalidURL: Returned when a `URLConvertible` type fails to create a valid `URL`.
  30. /// - parameterEncodingFailed: Returned when a parameter encoding object throws an error during the encoding process.
  31. /// - multipartEncodingFailed: Returned when some step in the multipart encoding process fails.
  32. /// - responseValidationFailed: Returned when a `validate()` call fails.
  33. /// - responseSerializationFailed: Returned when a response serializer encounters an error in the serialization process.
  34. /// - certificatePinningFailed: Returned when a response fails certificate pinning.
  35. public enum AFError: Error {
  36. /// The underlying reason the parameter encoding error occurred.
  37. ///
  38. /// - missingURL: The URL request did not have a URL to encode.
  39. /// - jsonEncodingFailed: JSON serialization failed with an underlying system error during the
  40. /// encoding process.
  41. public enum ParameterEncodingFailureReason {
  42. case missingURL
  43. case jsonEncodingFailed(error: Error)
  44. }
  45. /// The underlying reason the multipart encoding error occurred.
  46. ///
  47. /// - bodyPartURLInvalid: The `fileURL` provided for reading an encodable body part isn't a
  48. /// file URL.
  49. /// - bodyPartFilenameInvalid: The filename of the `fileURL` provided has either an empty
  50. /// `lastPathComponent` or `pathExtension.
  51. /// - bodyPartFileNotReachable: The file at the `fileURL` provided was not reachable.
  52. /// - bodyPartFileNotReachableWithError: Attempting to check the reachability of the `fileURL` provided threw
  53. /// an error.
  54. /// - bodyPartFileIsDirectory: The file at the `fileURL` provided is actually a directory.
  55. /// - bodyPartFileSizeNotAvailable: The size of the file at the `fileURL` provided was not returned by
  56. /// the system.
  57. /// - bodyPartFileSizeQueryFailedWithError: The attempt to find the size of the file at the `fileURL` provided
  58. /// threw an error.
  59. /// - bodyPartInputStreamCreationFailed: An `InputStream` could not be created for the provided `fileURL`.
  60. /// - outputStreamCreationFailed: An `OutputStream` could not be created when attempting to write the
  61. /// encoded data to disk.
  62. /// - outputStreamFileAlreadyExists: The encoded body data could not be writtent disk because a file
  63. /// already exists at the provided `fileURL`.
  64. /// - outputStreamURLInvalid: The `fileURL` provided for writing the encoded body data to disk is
  65. /// not a file URL.
  66. /// - outputStreamWriteFailed: The attempt to write the encoded body data to disk failed with an
  67. /// underlying error.
  68. /// - inputStreamReadFailed: The attempt to read an encoded body part `InputStream` failed with
  69. /// underlying system error.
  70. public enum MultipartEncodingFailureReason {
  71. case bodyPartURLInvalid(url: URL)
  72. case bodyPartFilenameInvalid(in: URL)
  73. case bodyPartFileNotReachable(at: URL)
  74. case bodyPartFileNotReachableWithError(atURL: URL, error: Error)
  75. case bodyPartFileIsDirectory(at: URL)
  76. case bodyPartFileSizeNotAvailable(at: URL)
  77. case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error)
  78. case bodyPartInputStreamCreationFailed(for: URL)
  79. case outputStreamCreationFailed(for: URL)
  80. case outputStreamFileAlreadyExists(at: URL)
  81. case outputStreamURLInvalid(url: URL)
  82. case outputStreamWriteFailed(error: Error)
  83. case inputStreamReadFailed(error: Error)
  84. }
  85. /// The underlying reason the response validation error occurred.
  86. ///
  87. /// - dataFileNil: The data file containing the server response did not exist.
  88. /// - dataFileReadFailed: The data file containing the server response could not be read.
  89. /// - missingContentType: The response did not contain a `Content-Type` and the `acceptableContentTypes`
  90. /// provided did not contain wildcard type.
  91. /// - unacceptableContentType: The response `Content-Type` did not match any type in the provided
  92. /// `acceptableContentTypes`.
  93. /// - unacceptableStatusCode: The response status code was not acceptable.
  94. public enum ResponseValidationFailureReason {
  95. case dataFileNil
  96. case dataFileReadFailed(at: URL)
  97. case missingContentType(acceptableContentTypes: [String])
  98. case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String)
  99. case unacceptableStatusCode(code: Int)
  100. }
  101. /// The underlying reason the response serialization error occurred.
  102. ///
  103. /// - inputDataNil: The server response contained no data.
  104. /// - inputDataNilOrZeroLength: The server response contained no data or the data was zero length.
  105. /// - inputFileNil: The file containing the server response did not exist.
  106. /// - inputFileReadFailed: The file containing the server response could not be read.
  107. /// - stringSerializationFailed: String serialization failed using the provided `String.Encoding`.
  108. /// - jsonSerializationFailed: JSON serialization failed with an underlying system error.
  109. /// - invalidEmptyResponse: Generic serialization failed for an empty response that wasn't type `Empty`.
  110. public enum ResponseSerializationFailureReason {
  111. case inputDataNil
  112. case inputDataNilOrZeroLength
  113. case inputFileNil
  114. case inputFileReadFailed(at: URL)
  115. case stringSerializationFailed(encoding: String.Encoding)
  116. case jsonSerializationFailed(error: Error)
  117. case invalidEmptyResponse(type: String)
  118. }
  119. public enum ServerTrustFailureReason {
  120. public struct Output {
  121. public let host: String
  122. public let trust: SecTrust
  123. public let status: OSStatus
  124. public let result: SecTrustResultType
  125. init(_ host: String, _ trust: SecTrust, _ status: OSStatus, _ result: SecTrustResultType) {
  126. self.host = host
  127. self.trust = trust
  128. self.status = status
  129. self.result = result
  130. }
  131. }
  132. case noRequiredEvaluator(host: String)
  133. case noCertificatesFound
  134. case noPublicKeysFound
  135. case policyApplicationFailed(trust: SecTrust, policy: SecPolicy, status: OSStatus)
  136. case settingAnchorCertificatesFailed(status: OSStatus, certificates: [SecCertificate])
  137. case revocationPolicyCreationFailed
  138. case defaultEvaluationFailed(output: Output)
  139. case hostValidationFailed(output: Output)
  140. case revocationCheckFailed(output: Output, options: RevocationTrustEvaluator.Options)
  141. case certificatePinningFailed(host: String, trust: SecTrust, pinnedCertificates: [SecCertificate], serverCertificates: [SecCertificate])
  142. case publicKeyPinningFailed(host: String, trust: SecTrust, pinnedKeys: [SecKey], serverKeys: [SecKey])
  143. }
  144. case explicitlyCancelled
  145. case invalidURL(url: URLConvertible)
  146. case parameterEncodingFailed(reason: ParameterEncodingFailureReason)
  147. case multipartEncodingFailed(reason: MultipartEncodingFailureReason)
  148. case responseValidationFailed(reason: ResponseValidationFailureReason)
  149. case responseSerializationFailed(reason: ResponseSerializationFailureReason)
  150. case serverTrustEvaluationFailed(reason: ServerTrustFailureReason)
  151. }
  152. public extension Error {
  153. /// Returns the instance cast as an `AFError`.
  154. public var asAFError: AFError? {
  155. return self as? AFError
  156. }
  157. }
  158. // MARK: - Error Booleans
  159. extension AFError {
  160. /// Returns whether the `AFError` is an explicitly cancelled error.
  161. public var isExplicitlyCancelledError: Bool {
  162. if case .explicitlyCancelled = self { return true }
  163. return false
  164. }
  165. /// Returns whether the AFError is an invalid URL error.
  166. public var isInvalidURLError: Bool {
  167. if case .invalidURL = self { return true }
  168. return false
  169. }
  170. /// Returns whether the AFError is a parameter encoding error. When `true`, the `underlyingError` property will
  171. /// contain the associated value.
  172. public var isParameterEncodingError: Bool {
  173. if case .parameterEncodingFailed = self { return true }
  174. return false
  175. }
  176. /// Returns whether the AFError is a multipart encoding error. When `true`, the `url` and `underlyingError` properties
  177. /// will contain the associated values.
  178. public var isMultipartEncodingError: Bool {
  179. if case .multipartEncodingFailed = self { return true }
  180. return false
  181. }
  182. /// Returns whether the `AFError` is a response validation error. When `true`, the `acceptableContentTypes`,
  183. /// `responseContentType`, and `responseCode` properties will contain the associated values.
  184. public var isResponseValidationError: Bool {
  185. if case .responseValidationFailed = self { return true }
  186. return false
  187. }
  188. /// Returns whether the `AFError` is a response serialization error. When `true`, the `failedStringEncoding` and
  189. /// `underlyingError` properties will contain the associated values.
  190. public var isResponseSerializationError: Bool {
  191. if case .responseSerializationFailed = self { return true }
  192. return false
  193. }
  194. /// Returns whether the `AFError` is a server trust evaluation error.
  195. public var isServerTrustEvaluationError: Bool {
  196. if case .serverTrustEvaluationFailed = self { return true }
  197. return false
  198. }
  199. }
  200. // MARK: - Convenience Properties
  201. extension AFError {
  202. /// The `URLConvertible` associated with the error.
  203. public var urlConvertible: URLConvertible? {
  204. switch self {
  205. case .invalidURL(let url):
  206. return url
  207. default:
  208. return nil
  209. }
  210. }
  211. /// The `URL` associated with the error.
  212. public var url: URL? {
  213. switch self {
  214. case .multipartEncodingFailed(let reason):
  215. return reason.url
  216. default:
  217. return nil
  218. }
  219. }
  220. /// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`,
  221. /// `.multipartEncodingFailed` or `.responseSerializationFailed` error.
  222. public var underlyingError: Error? {
  223. switch self {
  224. case .parameterEncodingFailed(let reason):
  225. return reason.underlyingError
  226. case .multipartEncodingFailed(let reason):
  227. return reason.underlyingError
  228. case .responseSerializationFailed(let reason):
  229. return reason.underlyingError
  230. default:
  231. return nil
  232. }
  233. }
  234. /// The acceptable `Content-Type`s of a `.responseValidationFailed` error.
  235. public var acceptableContentTypes: [String]? {
  236. switch self {
  237. case .responseValidationFailed(let reason):
  238. return reason.acceptableContentTypes
  239. default:
  240. return nil
  241. }
  242. }
  243. /// The response `Content-Type` of a `.responseValidationFailed` error.
  244. public var responseContentType: String? {
  245. switch self {
  246. case .responseValidationFailed(let reason):
  247. return reason.responseContentType
  248. default:
  249. return nil
  250. }
  251. }
  252. /// The response code of a `.responseValidationFailed` error.
  253. public var responseCode: Int? {
  254. switch self {
  255. case .responseValidationFailed(let reason):
  256. return reason.responseCode
  257. default:
  258. return nil
  259. }
  260. }
  261. /// The `String.Encoding` associated with a failed `.stringResponse()` call.
  262. public var failedStringEncoding: String.Encoding? {
  263. switch self {
  264. case .responseSerializationFailed(let reason):
  265. return reason.failedStringEncoding
  266. default:
  267. return nil
  268. }
  269. }
  270. }
  271. extension AFError.ParameterEncodingFailureReason {
  272. var underlyingError: Error? {
  273. switch self {
  274. case .jsonEncodingFailed(let error):
  275. return error
  276. default:
  277. return nil
  278. }
  279. }
  280. }
  281. extension AFError.MultipartEncodingFailureReason {
  282. var url: URL? {
  283. switch self {
  284. case .bodyPartURLInvalid(let url), .bodyPartFilenameInvalid(let url), .bodyPartFileNotReachable(let url),
  285. .bodyPartFileIsDirectory(let url), .bodyPartFileSizeNotAvailable(let url),
  286. .bodyPartInputStreamCreationFailed(let url), .outputStreamCreationFailed(let url),
  287. .outputStreamFileAlreadyExists(let url), .outputStreamURLInvalid(let url),
  288. .bodyPartFileNotReachableWithError(let url, _), .bodyPartFileSizeQueryFailedWithError(let url, _):
  289. return url
  290. default:
  291. return nil
  292. }
  293. }
  294. var underlyingError: Error? {
  295. switch self {
  296. case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error),
  297. .outputStreamWriteFailed(let error), .inputStreamReadFailed(let error):
  298. return error
  299. default:
  300. return nil
  301. }
  302. }
  303. }
  304. extension AFError.ResponseValidationFailureReason {
  305. var acceptableContentTypes: [String]? {
  306. switch self {
  307. case .missingContentType(let types), .unacceptableContentType(let types, _):
  308. return types
  309. default:
  310. return nil
  311. }
  312. }
  313. var responseContentType: String? {
  314. switch self {
  315. case .unacceptableContentType(_, let responseType):
  316. return responseType
  317. default:
  318. return nil
  319. }
  320. }
  321. var responseCode: Int? {
  322. switch self {
  323. case .unacceptableStatusCode(let code):
  324. return code
  325. default:
  326. return nil
  327. }
  328. }
  329. }
  330. extension AFError.ResponseSerializationFailureReason {
  331. var failedStringEncoding: String.Encoding? {
  332. switch self {
  333. case .stringSerializationFailed(let encoding):
  334. return encoding
  335. default:
  336. return nil
  337. }
  338. }
  339. var underlyingError: Error? {
  340. switch self {
  341. case .jsonSerializationFailed(let error):
  342. return error
  343. default:
  344. return nil
  345. }
  346. }
  347. }
  348. extension AFError.ServerTrustFailureReason {
  349. var output: AFError.ServerTrustFailureReason.Output? {
  350. switch self {
  351. case let .defaultEvaluationFailed(output),
  352. let .hostValidationFailed(output),
  353. let .revocationCheckFailed(output, _):
  354. return output
  355. default: return nil
  356. }
  357. }
  358. }
  359. // MARK: - Error Descriptions
  360. extension AFError: LocalizedError {
  361. public var errorDescription: String? {
  362. switch self {
  363. case .explicitlyCancelled:
  364. return "Request explicitly cancelled."
  365. case .invalidURL(let url):
  366. return "URL is not valid: \(url)"
  367. case .parameterEncodingFailed(let reason):
  368. return reason.localizedDescription
  369. case .multipartEncodingFailed(let reason):
  370. return reason.localizedDescription
  371. case .responseValidationFailed(let reason):
  372. return reason.localizedDescription
  373. case .responseSerializationFailed(let reason):
  374. return reason.localizedDescription
  375. case .serverTrustEvaluationFailed:
  376. return "Server trust evaluation failed."
  377. }
  378. }
  379. }
  380. extension AFError.ParameterEncodingFailureReason {
  381. var localizedDescription: String {
  382. switch self {
  383. case .missingURL:
  384. return "URL request to encode was missing a URL"
  385. case .jsonEncodingFailed(let error):
  386. return "JSON could not be encoded because of error:\n\(error.localizedDescription)"
  387. }
  388. }
  389. }
  390. extension AFError.MultipartEncodingFailureReason {
  391. var localizedDescription: String {
  392. switch self {
  393. case .bodyPartURLInvalid(let url):
  394. return "The URL provided is not a file URL: \(url)"
  395. case .bodyPartFilenameInvalid(let url):
  396. return "The URL provided does not have a valid filename: \(url)"
  397. case .bodyPartFileNotReachable(let url):
  398. return "The URL provided is not reachable: \(url)"
  399. case .bodyPartFileNotReachableWithError(let url, let error):
  400. return (
  401. "The system returned an error while checking the provided URL for " +
  402. "reachability.\nURL: \(url)\nError: \(error)"
  403. )
  404. case .bodyPartFileIsDirectory(let url):
  405. return "The URL provided is a directory: \(url)"
  406. case .bodyPartFileSizeNotAvailable(let url):
  407. return "Could not fetch the file size from the provided URL: \(url)"
  408. case .bodyPartFileSizeQueryFailedWithError(let url, let error):
  409. return (
  410. "The system returned an error while attempting to fetch the file size from the " +
  411. "provided URL.\nURL: \(url)\nError: \(error)"
  412. )
  413. case .bodyPartInputStreamCreationFailed(let url):
  414. return "Failed to create an InputStream for the provided URL: \(url)"
  415. case .outputStreamCreationFailed(let url):
  416. return "Failed to create an OutputStream for URL: \(url)"
  417. case .outputStreamFileAlreadyExists(let url):
  418. return "A file already exists at the provided URL: \(url)"
  419. case .outputStreamURLInvalid(let url):
  420. return "The provided OutputStream URL is invalid: \(url)"
  421. case .outputStreamWriteFailed(let error):
  422. return "OutputStream write failed with error: \(error)"
  423. case .inputStreamReadFailed(let error):
  424. return "InputStream read failed with error: \(error)"
  425. }
  426. }
  427. }
  428. extension AFError.ResponseSerializationFailureReason {
  429. var localizedDescription: String {
  430. switch self {
  431. case .inputDataNil:
  432. return "Response could not be serialized, input data was nil."
  433. case .inputDataNilOrZeroLength:
  434. return "Response could not be serialized, input data was nil or zero length."
  435. case .inputFileNil:
  436. return "Response could not be serialized, input file was nil."
  437. case .inputFileReadFailed(let url):
  438. return "Response could not be serialized, input file could not be read: \(url)."
  439. case .stringSerializationFailed(let encoding):
  440. return "String could not be serialized with encoding: \(encoding)."
  441. case .jsonSerializationFailed(let error):
  442. return "JSON could not be serialized because of error:\n\(error.localizedDescription)"
  443. case .invalidEmptyResponse(let type):
  444. return "Empty response could not be serialized to type: \(type). Use Empty as the expected type for such responses."
  445. }
  446. }
  447. }
  448. extension AFError.ResponseValidationFailureReason {
  449. var localizedDescription: String {
  450. switch self {
  451. case .dataFileNil:
  452. return "Response could not be validated, data file was nil."
  453. case .dataFileReadFailed(let url):
  454. return "Response could not be validated, data file could not be read: \(url)."
  455. case .missingContentType(let types):
  456. return (
  457. "Response Content-Type was missing and acceptable content types " +
  458. "(\(types.joined(separator: ","))) do not match \"*/*\"."
  459. )
  460. case .unacceptableContentType(let acceptableTypes, let responseType):
  461. return (
  462. "Response Content-Type \"\(responseType)\" does not match any acceptable types: " +
  463. "\(acceptableTypes.joined(separator: ","))."
  464. )
  465. case .unacceptableStatusCode(let code):
  466. return "Response status code was unacceptable: \(code)."
  467. }
  468. }
  469. }
  470. extension AFError.ServerTrustFailureReason {
  471. var localizedDescription: String {
  472. switch self {
  473. case let .noRequiredEvaluator(host):
  474. return "A ServerTrustEvaluating value is required for host \(host) but none was found."
  475. case .noCertificatesFound:
  476. return "No certificates were found or provided for evaluation."
  477. case .noPublicKeysFound:
  478. return "No public keys were found or provided for evaluation."
  479. case .policyApplicationFailed:
  480. return "Attempting to set a SecPolicy failed."
  481. case .settingAnchorCertificatesFailed:
  482. return "Attempting to set the provided certificates as anchor certificates failed."
  483. case .revocationPolicyCreationFailed:
  484. return "Attempting to create a revocation policy failed."
  485. case let .defaultEvaluationFailed(output):
  486. return "Default evaluation failed for host \(output.host)."
  487. case let .hostValidationFailed(output):
  488. return "Host validation failed for host \(output.host)."
  489. case let .revocationCheckFailed(output, _):
  490. return "Revocation check failed for host \(output.host)."
  491. case let .certificatePinningFailed(host, _, _, _):
  492. return "Certificate pinning failed for host \(host)."
  493. case let .publicKeyPinningFailed(host, _, _, _):
  494. return "Public key pinning failed for host \(host)."
  495. }
  496. }
  497. }