AFError.swift 16 KB

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