AFError.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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: - Adapt Error
  133. struct AdaptError: Error {
  134. let error: Error
  135. }
  136. extension Error {
  137. var underlyingAdaptError: Error? { return (self as? AdaptError)?.error }
  138. }
  139. // MARK: - Error Booleans
  140. extension AFError {
  141. /// Returns whether the `AFError` is an explicitly cancelled error.
  142. public var isExplicitlyCancelledError: Bool {
  143. if case .explicitlyCancelled = self { return true }
  144. return false
  145. }
  146. /// Returns whether the AFError is an invalid URL error.
  147. public var isInvalidURLError: Bool {
  148. if case .invalidURL = self { return true }
  149. return false
  150. }
  151. /// Returns whether the AFError is a parameter encoding error. When `true`, the `underlyingError` property will
  152. /// contain the associated value.
  153. public var isParameterEncodingError: Bool {
  154. if case .parameterEncodingFailed = self { return true }
  155. return false
  156. }
  157. /// Returns whether the AFError is a multipart encoding error. When `true`, the `url` and `underlyingError` properties
  158. /// will contain the associated values.
  159. public var isMultipartEncodingError: Bool {
  160. if case .multipartEncodingFailed = self { return true }
  161. return false
  162. }
  163. /// Returns whether the `AFError` is a response validation error. When `true`, the `acceptableContentTypes`,
  164. /// `responseContentType`, and `responseCode` properties will contain the associated values.
  165. public var isResponseValidationError: Bool {
  166. if case .responseValidationFailed = self { return true }
  167. return false
  168. }
  169. /// Returns whether the `AFError` is a response serialization error. When `true`, the `failedStringEncoding` and
  170. /// `underlyingError` properties will contain the associated values.
  171. public var isResponseSerializationError: Bool {
  172. if case .responseSerializationFailed = self { return true }
  173. return false
  174. }
  175. /// Returns whether the `AFError` is a certificate pinning error.
  176. public var isCertificatePinningError: Bool {
  177. if case .certificatePinningFailed = self { return true }
  178. return false
  179. }
  180. }
  181. // MARK: - Convenience Properties
  182. extension AFError {
  183. /// The `URLConvertible` associated with the error.
  184. public var urlConvertible: URLConvertible? {
  185. switch self {
  186. case .invalidURL(let url):
  187. return url
  188. default:
  189. return nil
  190. }
  191. }
  192. /// The `URL` associated with the error.
  193. public var url: URL? {
  194. switch self {
  195. case .multipartEncodingFailed(let reason):
  196. return reason.url
  197. default:
  198. return nil
  199. }
  200. }
  201. /// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`,
  202. /// `.multipartEncodingFailed` or `.responseSerializationFailed` error.
  203. public var underlyingError: Error? {
  204. switch self {
  205. case .parameterEncodingFailed(let reason):
  206. return reason.underlyingError
  207. case .multipartEncodingFailed(let reason):
  208. return reason.underlyingError
  209. case .responseSerializationFailed(let reason):
  210. return reason.underlyingError
  211. default:
  212. return nil
  213. }
  214. }
  215. /// The acceptable `Content-Type`s of a `.responseValidationFailed` error.
  216. public var acceptableContentTypes: [String]? {
  217. switch self {
  218. case .responseValidationFailed(let reason):
  219. return reason.acceptableContentTypes
  220. default:
  221. return nil
  222. }
  223. }
  224. /// The response `Content-Type` of a `.responseValidationFailed` error.
  225. public var responseContentType: String? {
  226. switch self {
  227. case .responseValidationFailed(let reason):
  228. return reason.responseContentType
  229. default:
  230. return nil
  231. }
  232. }
  233. /// The response code of a `.responseValidationFailed` error.
  234. public var responseCode: Int? {
  235. switch self {
  236. case .responseValidationFailed(let reason):
  237. return reason.responseCode
  238. default:
  239. return nil
  240. }
  241. }
  242. /// The `String.Encoding` associated with a failed `.stringResponse()` call.
  243. public var failedStringEncoding: String.Encoding? {
  244. switch self {
  245. case .responseSerializationFailed(let reason):
  246. return reason.failedStringEncoding
  247. default:
  248. return nil
  249. }
  250. }
  251. }
  252. extension AFError.ParameterEncodingFailureReason {
  253. var underlyingError: Error? {
  254. switch self {
  255. case .jsonEncodingFailed(let error), .propertyListEncodingFailed(let error):
  256. return error
  257. default:
  258. return nil
  259. }
  260. }
  261. }
  262. extension AFError.MultipartEncodingFailureReason {
  263. var url: URL? {
  264. switch self {
  265. case .bodyPartURLInvalid(let url), .bodyPartFilenameInvalid(let url), .bodyPartFileNotReachable(let url),
  266. .bodyPartFileIsDirectory(let url), .bodyPartFileSizeNotAvailable(let url),
  267. .bodyPartInputStreamCreationFailed(let url), .outputStreamCreationFailed(let url),
  268. .outputStreamFileAlreadyExists(let url), .outputStreamURLInvalid(let url),
  269. .bodyPartFileNotReachableWithError(let url, _), .bodyPartFileSizeQueryFailedWithError(let url, _):
  270. return url
  271. default:
  272. return nil
  273. }
  274. }
  275. var underlyingError: Error? {
  276. switch self {
  277. case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error),
  278. .outputStreamWriteFailed(let error), .inputStreamReadFailed(let error):
  279. return error
  280. default:
  281. return nil
  282. }
  283. }
  284. }
  285. extension AFError.ResponseValidationFailureReason {
  286. var acceptableContentTypes: [String]? {
  287. switch self {
  288. case .missingContentType(let types), .unacceptableContentType(let types, _):
  289. return types
  290. default:
  291. return nil
  292. }
  293. }
  294. var responseContentType: String? {
  295. switch self {
  296. case .unacceptableContentType(_, let responseType):
  297. return responseType
  298. default:
  299. return nil
  300. }
  301. }
  302. var responseCode: Int? {
  303. switch self {
  304. case .unacceptableStatusCode(let code):
  305. return code
  306. default:
  307. return nil
  308. }
  309. }
  310. }
  311. extension AFError.ResponseSerializationFailureReason {
  312. var failedStringEncoding: String.Encoding? {
  313. switch self {
  314. case .stringSerializationFailed(let encoding):
  315. return encoding
  316. default:
  317. return nil
  318. }
  319. }
  320. var underlyingError: Error? {
  321. switch self {
  322. case .jsonSerializationFailed(let error), .propertyListSerializationFailed(let error):
  323. return error
  324. default:
  325. return nil
  326. }
  327. }
  328. }
  329. // MARK: - Error Descriptions
  330. extension AFError: LocalizedError {
  331. public var errorDescription: String? {
  332. switch self {
  333. case .invalidURL(let url):
  334. return "URL is not valid: \(url)"
  335. case .parameterEncodingFailed(let reason):
  336. return reason.localizedDescription
  337. case .multipartEncodingFailed(let reason):
  338. return reason.localizedDescription
  339. case .responseValidationFailed(let reason):
  340. return reason.localizedDescription
  341. case .responseSerializationFailed(let reason):
  342. return reason.localizedDescription
  343. case .explicitlyCancelled:
  344. return "Request explicitly cancelled."
  345. case .certificatePinningFailed:
  346. return "Certificate pinning failed."
  347. }
  348. }
  349. }
  350. extension AFError.ParameterEncodingFailureReason {
  351. var localizedDescription: String {
  352. switch self {
  353. case .missingURL:
  354. return "URL request to encode was missing a URL"
  355. case .jsonEncodingFailed(let error):
  356. return "JSON could not be encoded because of error:\n\(error.localizedDescription)"
  357. case .propertyListEncodingFailed(let error):
  358. return "PropertyList could not be encoded because of error:\n\(error.localizedDescription)"
  359. }
  360. }
  361. }
  362. extension AFError.MultipartEncodingFailureReason {
  363. var localizedDescription: String {
  364. switch self {
  365. case .bodyPartURLInvalid(let url):
  366. return "The URL provided is not a file URL: \(url)"
  367. case .bodyPartFilenameInvalid(let url):
  368. return "The URL provided does not have a valid filename: \(url)"
  369. case .bodyPartFileNotReachable(let url):
  370. return "The URL provided is not reachable: \(url)"
  371. case .bodyPartFileNotReachableWithError(let url, let error):
  372. return (
  373. "The system returned an error while checking the provided URL for " +
  374. "reachability.\nURL: \(url)\nError: \(error)"
  375. )
  376. case .bodyPartFileIsDirectory(let url):
  377. return "The URL provided is a directory: \(url)"
  378. case .bodyPartFileSizeNotAvailable(let url):
  379. return "Could not fetch the file size from the provided URL: \(url)"
  380. case .bodyPartFileSizeQueryFailedWithError(let url, let error):
  381. return (
  382. "The system returned an error while attempting to fetch the file size from the " +
  383. "provided URL.\nURL: \(url)\nError: \(error)"
  384. )
  385. case .bodyPartInputStreamCreationFailed(let url):
  386. return "Failed to create an InputStream for the provided URL: \(url)"
  387. case .outputStreamCreationFailed(let url):
  388. return "Failed to create an OutputStream for URL: \(url)"
  389. case .outputStreamFileAlreadyExists(let url):
  390. return "A file already exists at the provided URL: \(url)"
  391. case .outputStreamURLInvalid(let url):
  392. return "The provided OutputStream URL is invalid: \(url)"
  393. case .outputStreamWriteFailed(let error):
  394. return "OutputStream write failed with error: \(error)"
  395. case .inputStreamReadFailed(let error):
  396. return "InputStream read failed with error: \(error)"
  397. }
  398. }
  399. }
  400. extension AFError.ResponseSerializationFailureReason {
  401. var localizedDescription: String {
  402. switch self {
  403. case .inputDataNil:
  404. return "Response could not be serialized, input data was nil."
  405. case .inputDataNilOrZeroLength:
  406. return "Response could not be serialized, input data was nil or zero length."
  407. case .inputFileNil:
  408. return "Response could not be serialized, input file was nil."
  409. case .inputFileReadFailed(let url):
  410. return "Response could not be serialized, input file could not be read: \(url)."
  411. case .stringSerializationFailed(let encoding):
  412. return "String could not be serialized with encoding: \(encoding)."
  413. case .jsonSerializationFailed(let error):
  414. return "JSON could not be serialized because of error:\n\(error.localizedDescription)"
  415. case .propertyListSerializationFailed(let error):
  416. return "PropertyList could not be serialized because of error:\n\(error.localizedDescription)"
  417. case .invalidEmptyResponse(let type):
  418. return "Empty response could not be serialized to type: \(type). Use Empty as the expected type for such responses."
  419. }
  420. }
  421. }
  422. extension AFError.ResponseValidationFailureReason {
  423. var localizedDescription: String {
  424. switch self {
  425. case .dataFileNil:
  426. return "Response could not be validated, data file was nil."
  427. case .dataFileReadFailed(let url):
  428. return "Response could not be validated, data file could not be read: \(url)."
  429. case .missingContentType(let types):
  430. return (
  431. "Response Content-Type was missing and acceptable content types " +
  432. "(\(types.joined(separator: ","))) do not match \"*/*\"."
  433. )
  434. case .unacceptableContentType(let acceptableTypes, let responseType):
  435. return (
  436. "Response Content-Type \"\(responseType)\" does not match any acceptable types: " +
  437. "\(acceptableTypes.joined(separator: ","))."
  438. )
  439. case .unacceptableStatusCode(let code):
  440. return "Response status code was unacceptable: \(code)."
  441. }
  442. }
  443. }