AFError.swift 18 KB

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