AFError.swift 17 KB

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