AFError.swift 19 KB

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