AFError.swift 20 KB

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