AFError.swift 18 KB

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