AFError.swift 19 KB

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