AFError.swift 19 KB

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