AFError.swift 19 KB

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