AFError.swift 17 KB

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