AFError.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. /// - propertyListEncodingFailed: Property list serialization failed with an underlying system error during
  42. /// encoding process.
  43. public enum ParameterEncodingFailureReason {
  44. case missingURL
  45. case jsonEncodingFailed(error: Error)
  46. case propertyListEncodingFailed(error: Error)
  47. }
  48. /// The underlying reason the multipart encoding error occurred.
  49. ///
  50. /// - bodyPartURLInvalid: The `fileURL` provided for reading an encodable body part isn't a
  51. /// file URL.
  52. /// - bodyPartFilenameInvalid: The filename of the `fileURL` provided has either an empty
  53. /// `lastPathComponent` or `pathExtension.
  54. /// - bodyPartFileNotReachable: The file at the `fileURL` provided was not reachable.
  55. /// - bodyPartFileNotReachableWithError: Attempting to check the reachability of the `fileURL` provided threw
  56. /// an error.
  57. /// - bodyPartFileIsDirectory: The file at the `fileURL` provided is actually a directory.
  58. /// - bodyPartFileSizeNotAvailable: The size of the file at the `fileURL` provided was not returned by
  59. /// the system.
  60. /// - bodyPartFileSizeQueryFailedWithError: The attempt to find the size of the file at the `fileURL` provided
  61. /// threw an error.
  62. /// - bodyPartInputStreamCreationFailed: An `InputStream` could not be created for the provided `fileURL`.
  63. /// - outputStreamCreationFailed: An `OutputStream` could not be created when attempting to write the
  64. /// encoded data to disk.
  65. /// - outputStreamFileAlreadyExists: The encoded body data could not be writtent disk because a file
  66. /// already exists at the provided `fileURL`.
  67. /// - outputStreamURLInvalid: The `fileURL` provided for writing the encoded body data to disk is
  68. /// not a file URL.
  69. /// - outputStreamWriteFailed: The attempt to write the encoded body data to disk failed with an
  70. /// underlying error.
  71. /// - inputStreamReadFailed: The attempt to read an encoded body part `InputStream` failed with
  72. /// underlying system error.
  73. public enum MultipartEncodingFailureReason {
  74. case bodyPartURLInvalid(url: URL)
  75. case bodyPartFilenameInvalid(in: URL)
  76. case bodyPartFileNotReachable(at: URL)
  77. case bodyPartFileNotReachableWithError(atURL: URL, error: Error)
  78. case bodyPartFileIsDirectory(at: URL)
  79. case bodyPartFileSizeNotAvailable(at: URL)
  80. case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error)
  81. case bodyPartInputStreamCreationFailed(for: URL)
  82. case outputStreamCreationFailed(for: URL)
  83. case outputStreamFileAlreadyExists(at: URL)
  84. case outputStreamURLInvalid(url: URL)
  85. case outputStreamWriteFailed(error: Error)
  86. case inputStreamReadFailed(error: Error)
  87. }
  88. /// The underlying reason the response validation error occurred.
  89. ///
  90. /// - dataFileNil: The data file containing the server response did not exist.
  91. /// - dataFileReadFailed: The data file containing the server response could not be read.
  92. /// - missingContentType: The response did not contain a `Content-Type` and the `acceptableContentTypes`
  93. /// provided did not contain wildcard type.
  94. /// - unacceptableContentType: The response `Content-Type` did not match any type in the provided
  95. /// `acceptableContentTypes`.
  96. /// - unacceptableStatusCode: The response status code was not acceptable.
  97. public enum ResponseValidationFailureReason {
  98. case dataFileNil
  99. case dataFileReadFailed(at: URL)
  100. case missingContentType(acceptableContentTypes: [String])
  101. case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String)
  102. case unacceptableStatusCode(code: Int)
  103. }
  104. /// The underlying reason the response serialization error occurred.
  105. ///
  106. /// - inputDataNil: The server response contained no data.
  107. /// - inputDataNilOrZeroLength: The server response contained no data or the data was zero length.
  108. /// - inputFileNil: The file containing the server response did not exist.
  109. /// - inputFileReadFailed: The file containing the server response could not be read.
  110. /// - stringSerializationFailed: String serialization failed using the provided `String.Encoding`.
  111. /// - jsonSerializationFailed: JSON serialization failed with an underlying system error.
  112. /// - propertyListSerializationFailed: Property list serialization failed with an underlying system error.
  113. /// - invalidEmptyResponse: Generic serialization failed for an empty response that wasn't type `Empty`.
  114. public enum ResponseSerializationFailureReason {
  115. case inputDataNil
  116. case inputDataNilOrZeroLength
  117. case inputFileNil
  118. case inputFileReadFailed(at: URL)
  119. case stringSerializationFailed(encoding: String.Encoding)
  120. case jsonSerializationFailed(error: Error)
  121. case propertyListSerializationFailed(error: Error)
  122. case invalidEmptyResponse(type: String)
  123. }
  124. case explicitlyCancelled
  125. case invalidURL(url: URLConvertible)
  126. case parameterEncodingFailed(reason: ParameterEncodingFailureReason)
  127. case multipartEncodingFailed(reason: MultipartEncodingFailureReason)
  128. case responseValidationFailed(reason: ResponseValidationFailureReason)
  129. case responseSerializationFailed(reason: ResponseSerializationFailureReason)
  130. case certificatePinningFailed
  131. }
  132. // MARK: - Error Booleans
  133. extension AFError {
  134. /// Returns whether the `AFError` is an explicitly cancelled error.
  135. public var isExplicitlyCancelledError: Bool {
  136. if case .explicitlyCancelled = self { return true }
  137. return false
  138. }
  139. /// Returns whether the AFError is an invalid URL error.
  140. public var isInvalidURLError: Bool {
  141. if case .invalidURL = self { return true }
  142. return false
  143. }
  144. /// Returns whether the AFError is a parameter encoding error. When `true`, the `underlyingError` property will
  145. /// contain the associated value.
  146. public var isParameterEncodingError: Bool {
  147. if case .parameterEncodingFailed = self { return true }
  148. return false
  149. }
  150. /// Returns whether the AFError is a multipart encoding error. When `true`, the `url` and `underlyingError` properties
  151. /// will contain the associated values.
  152. public var isMultipartEncodingError: Bool {
  153. if case .multipartEncodingFailed = self { return true }
  154. return false
  155. }
  156. /// Returns whether the `AFError` is a response validation error. When `true`, the `acceptableContentTypes`,
  157. /// `responseContentType`, and `responseCode` properties will contain the associated values.
  158. public var isResponseValidationError: Bool {
  159. if case .responseValidationFailed = self { return true }
  160. return false
  161. }
  162. /// Returns whether the `AFError` is a response serialization error. When `true`, the `failedStringEncoding` and
  163. /// `underlyingError` properties will contain the associated values.
  164. public var isResponseSerializationError: Bool {
  165. if case .responseSerializationFailed = self { return true }
  166. return false
  167. }
  168. /// Returns whether the `AFError` is a certificate pinning error.
  169. public var isCertificatePinningError: Bool {
  170. if case .certificatePinningFailed = self { return true }
  171. return false
  172. }
  173. }
  174. // MARK: - Convenience Properties
  175. extension AFError {
  176. /// The `URLConvertible` associated with the error.
  177. public var urlConvertible: URLConvertible? {
  178. switch self {
  179. case .invalidURL(let url):
  180. return url
  181. default:
  182. return nil
  183. }
  184. }
  185. /// The `URL` associated with the error.
  186. public var url: URL? {
  187. switch self {
  188. case .multipartEncodingFailed(let reason):
  189. return reason.url
  190. default:
  191. return nil
  192. }
  193. }
  194. /// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`,
  195. /// `.multipartEncodingFailed` or `.responseSerializationFailed` error.
  196. public var underlyingError: Error? {
  197. switch self {
  198. case .parameterEncodingFailed(let reason):
  199. return reason.underlyingError
  200. case .multipartEncodingFailed(let reason):
  201. return reason.underlyingError
  202. case .responseSerializationFailed(let reason):
  203. return reason.underlyingError
  204. default:
  205. return nil
  206. }
  207. }
  208. /// The acceptable `Content-Type`s of a `.responseValidationFailed` error.
  209. public var acceptableContentTypes: [String]? {
  210. switch self {
  211. case .responseValidationFailed(let reason):
  212. return reason.acceptableContentTypes
  213. default:
  214. return nil
  215. }
  216. }
  217. /// The response `Content-Type` of a `.responseValidationFailed` error.
  218. public var responseContentType: String? {
  219. switch self {
  220. case .responseValidationFailed(let reason):
  221. return reason.responseContentType
  222. default:
  223. return nil
  224. }
  225. }
  226. /// The response code of a `.responseValidationFailed` error.
  227. public var responseCode: Int? {
  228. switch self {
  229. case .responseValidationFailed(let reason):
  230. return reason.responseCode
  231. default:
  232. return nil
  233. }
  234. }
  235. /// The `String.Encoding` associated with a failed `.stringResponse()` call.
  236. public var failedStringEncoding: String.Encoding? {
  237. switch self {
  238. case .responseSerializationFailed(let reason):
  239. return reason.failedStringEncoding
  240. default:
  241. return nil
  242. }
  243. }
  244. }
  245. extension AFError.ParameterEncodingFailureReason {
  246. var underlyingError: Error? {
  247. switch self {
  248. case .jsonEncodingFailed(let error), .propertyListEncodingFailed(let error):
  249. return error
  250. default:
  251. return nil
  252. }
  253. }
  254. }
  255. extension AFError.MultipartEncodingFailureReason {
  256. var url: URL? {
  257. switch self {
  258. case .bodyPartURLInvalid(let url), .bodyPartFilenameInvalid(let url), .bodyPartFileNotReachable(let url),
  259. .bodyPartFileIsDirectory(let url), .bodyPartFileSizeNotAvailable(let url),
  260. .bodyPartInputStreamCreationFailed(let url), .outputStreamCreationFailed(let url),
  261. .outputStreamFileAlreadyExists(let url), .outputStreamURLInvalid(let url),
  262. .bodyPartFileNotReachableWithError(let url, _), .bodyPartFileSizeQueryFailedWithError(let url, _):
  263. return url
  264. default:
  265. return nil
  266. }
  267. }
  268. var underlyingError: Error? {
  269. switch self {
  270. case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error),
  271. .outputStreamWriteFailed(let error), .inputStreamReadFailed(let error):
  272. return error
  273. default:
  274. return nil
  275. }
  276. }
  277. }
  278. extension AFError.ResponseValidationFailureReason {
  279. var acceptableContentTypes: [String]? {
  280. switch self {
  281. case .missingContentType(let types), .unacceptableContentType(let types, _):
  282. return types
  283. default:
  284. return nil
  285. }
  286. }
  287. var responseContentType: String? {
  288. switch self {
  289. case .unacceptableContentType(_, let responseType):
  290. return responseType
  291. default:
  292. return nil
  293. }
  294. }
  295. var responseCode: Int? {
  296. switch self {
  297. case .unacceptableStatusCode(let code):
  298. return code
  299. default:
  300. return nil
  301. }
  302. }
  303. }
  304. extension AFError.ResponseSerializationFailureReason {
  305. var failedStringEncoding: String.Encoding? {
  306. switch self {
  307. case .stringSerializationFailed(let encoding):
  308. return encoding
  309. default:
  310. return nil
  311. }
  312. }
  313. var underlyingError: Error? {
  314. switch self {
  315. case .jsonSerializationFailed(let error), .propertyListSerializationFailed(let error):
  316. return error
  317. default:
  318. return nil
  319. }
  320. }
  321. }
  322. // MARK: - Error Descriptions
  323. extension AFError: LocalizedError {
  324. public var errorDescription: String? {
  325. switch self {
  326. case .invalidURL(let url):
  327. return "URL is not valid: \(url)"
  328. case .parameterEncodingFailed(let reason):
  329. return reason.localizedDescription
  330. case .multipartEncodingFailed(let reason):
  331. return reason.localizedDescription
  332. case .responseValidationFailed(let reason):
  333. return reason.localizedDescription
  334. case .responseSerializationFailed(let reason):
  335. return reason.localizedDescription
  336. case .explicitlyCancelled:
  337. return "Request explicitly cancelled."
  338. case .certificatePinningFailed:
  339. return "Certificate pinning failed."
  340. }
  341. }
  342. }
  343. extension AFError.ParameterEncodingFailureReason {
  344. var localizedDescription: String {
  345. switch self {
  346. case .missingURL:
  347. return "URL request to encode was missing a URL"
  348. case .jsonEncodingFailed(let error):
  349. return "JSON could not be encoded because of error:\n\(error.localizedDescription)"
  350. case .propertyListEncodingFailed(let error):
  351. return "PropertyList could not be encoded because of error:\n\(error.localizedDescription)"
  352. }
  353. }
  354. }
  355. extension AFError.MultipartEncodingFailureReason {
  356. var localizedDescription: String {
  357. switch self {
  358. case .bodyPartURLInvalid(let url):
  359. return "The URL provided is not a file URL: \(url)"
  360. case .bodyPartFilenameInvalid(let url):
  361. return "The URL provided does not have a valid filename: \(url)"
  362. case .bodyPartFileNotReachable(let url):
  363. return "The URL provided is not reachable: \(url)"
  364. case .bodyPartFileNotReachableWithError(let url, let error):
  365. return (
  366. "The system returned an error while checking the provided URL for " +
  367. "reachability.\nURL: \(url)\nError: \(error)"
  368. )
  369. case .bodyPartFileIsDirectory(let url):
  370. return "The URL provided is a directory: \(url)"
  371. case .bodyPartFileSizeNotAvailable(let url):
  372. return "Could not fetch the file size from the provided URL: \(url)"
  373. case .bodyPartFileSizeQueryFailedWithError(let url, let error):
  374. return (
  375. "The system returned an error while attempting to fetch the file size from the " +
  376. "provided URL.\nURL: \(url)\nError: \(error)"
  377. )
  378. case .bodyPartInputStreamCreationFailed(let url):
  379. return "Failed to create an InputStream for the provided URL: \(url)"
  380. case .outputStreamCreationFailed(let url):
  381. return "Failed to create an OutputStream for URL: \(url)"
  382. case .outputStreamFileAlreadyExists(let url):
  383. return "A file already exists at the provided URL: \(url)"
  384. case .outputStreamURLInvalid(let url):
  385. return "The provided OutputStream URL is invalid: \(url)"
  386. case .outputStreamWriteFailed(let error):
  387. return "OutputStream write failed with error: \(error)"
  388. case .inputStreamReadFailed(let error):
  389. return "InputStream read failed with error: \(error)"
  390. }
  391. }
  392. }
  393. extension AFError.ResponseSerializationFailureReason {
  394. var localizedDescription: String {
  395. switch self {
  396. case .inputDataNil:
  397. return "Response could not be serialized, input data was nil."
  398. case .inputDataNilOrZeroLength:
  399. return "Response could not be serialized, input data was nil or zero length."
  400. case .inputFileNil:
  401. return "Response could not be serialized, input file was nil."
  402. case .inputFileReadFailed(let url):
  403. return "Response could not be serialized, input file could not be read: \(url)."
  404. case .stringSerializationFailed(let encoding):
  405. return "String could not be serialized with encoding: \(encoding)."
  406. case .jsonSerializationFailed(let error):
  407. return "JSON could not be serialized because of error:\n\(error.localizedDescription)"
  408. case .propertyListSerializationFailed(let error):
  409. return "PropertyList could not be serialized because of error:\n\(error.localizedDescription)"
  410. case .invalidEmptyResponse(let type):
  411. return "Empty response could not be serialized to type: \(type). Use Empty as the expected type for such responses."
  412. }
  413. }
  414. }
  415. extension AFError.ResponseValidationFailureReason {
  416. var localizedDescription: String {
  417. switch self {
  418. case .dataFileNil:
  419. return "Response could not be validated, data file was nil."
  420. case .dataFileReadFailed(let url):
  421. return "Response could not be validated, data file could not be read: \(url)."
  422. case .missingContentType(let types):
  423. return (
  424. "Response Content-Type was missing and acceptable content types " +
  425. "(\(types.joined(separator: ","))) do not match \"*/*\"."
  426. )
  427. case .unacceptableContentType(let acceptableTypes, let responseType):
  428. return (
  429. "Response Content-Type \"\(responseType)\" does not match any acceptable types: " +
  430. "\(acceptableTypes.joined(separator: ","))."
  431. )
  432. case .unacceptableStatusCode(let code):
  433. return "Response status code was unacceptable: \(code)."
  434. }
  435. }
  436. }