KingfisherError.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. //
  2. // KingfisherError.swift
  3. // Kingfisher
  4. //
  5. // Created by onevcat on 2018/09/26.
  6. //
  7. // Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. import Foundation
  27. extension Never {}
  28. /// Represents all the errors which can happen in Kingfisher framework.
  29. /// Kingfisher related methods always throw a `KingfisherError` or invoke the callback with `KingfisherError`
  30. /// as its error type. To handle errors from Kingfisher, you switch over the error to get a reason catalog,
  31. /// then switch over the reason to know error detail.
  32. public enum KingfisherError: Error {
  33. // MARK: Error Reason Types
  34. /// Represents the error reason during networking request phase.
  35. ///
  36. /// - emptyRequest: The request is empty. Code 1001.
  37. /// - invalidURL: The URL of request is invalid. Code 1002.
  38. /// - taskCancelled: The downloading task is cancelled by user. Code 1003.
  39. public enum RequestErrorReason {
  40. /// The request is empty. Code 1001.
  41. case emptyRequest
  42. /// The URL of request is invalid. Code 1002.
  43. /// - request: The request is tend to be sent but its URL is invalid.
  44. case invalidURL(request: URLRequest)
  45. /// The downloading task is cancelled by user. Code 1003.
  46. /// - task: The session data task which is cancelled.
  47. /// - token: The cancel token which is used for cancelling the task.
  48. case taskCancelled(task: SessionDataTask, token: SessionDataTask.CancelToken)
  49. }
  50. /// Represents the error reason during networking response phase.
  51. ///
  52. /// - invalidURLResponse: The response is not a valid URL response. Code 2001.
  53. /// - invalidHTTPStatusCode: The response contains an invalid HTTP status code. Code 2002.
  54. /// - URLSessionError: An error happens in the system URL session. Code 2003.
  55. /// - dataModifyingFailed: Data modifying fails on returning a valid data. Code 2004.
  56. /// - noURLResponse: The task is done but no URL response found. Code 2005.
  57. public enum ResponseErrorReason {
  58. /// The response is not a valid URL response. Code 2001.
  59. /// - response: The received invalid URL response.
  60. /// The response is expected to be an HTTP response, but it is not.
  61. case invalidURLResponse(response: URLResponse)
  62. /// The response contains an invalid HTTP status code. Code 2002.
  63. /// - Note:
  64. /// By default, status code 200..<400 is recognized as valid. You can override
  65. /// this behavior by conforming to the `ImageDownloaderDelegate`.
  66. /// - response: The received response.
  67. case invalidHTTPStatusCode(response: HTTPURLResponse)
  68. /// An error happens in the system URL session. Code 2003.
  69. /// - error: The underlying URLSession error object.
  70. case URLSessionError(error: Error)
  71. /// Data modifying fails on returning a valid data. Code 2004.
  72. /// - task: The failed task.
  73. case dataModifyingFailed(task: SessionDataTask)
  74. /// The task is done but no URL response found. Code 2005.
  75. /// - task: The failed task.
  76. case noURLResponse(task: SessionDataTask)
  77. }
  78. /// Represents the error reason during Kingfisher caching system.
  79. ///
  80. /// - fileEnumeratorCreationFailed: Cannot create a file enumerator for a certain disk URL. Code 3001.
  81. /// - invalidFileEnumeratorContent: Cannot get correct file contents from a file enumerator. Code 3002.
  82. /// - invalidURLResource: The file at target URL exists, but its URL resource is unavailable. Code 3003.
  83. /// - cannotLoadDataFromDisk: The file at target URL exists, but the data cannot be loaded from it. Code 3004.
  84. /// - cannotCreateDirectory: Cannot create a folder at a given path. Code 3005.
  85. /// - imageNotExisting: The requested image does not exist in cache. Code 3006.
  86. /// - cannotConvertToData: Cannot convert an object to data for storing. Code 3007.
  87. /// - cannotSerializeImage: Cannot serialize an image to data for storing. Code 3008.
  88. public enum CacheErrorReason {
  89. /// Cannot create a file enumerator for a certain disk URL. Code 3001.
  90. /// - url: The target disk URL from which the file enumerator should be created.
  91. case fileEnumeratorCreationFailed(url: URL)
  92. /// Cannot get correct file contents from a file enumerator. Code 3002.
  93. /// - url: The target disk URL from which the content of a file enumerator should be got.
  94. case invalidFileEnumeratorContent(url: URL)
  95. /// The file at target URL exists, but its URL resource is unavailable. Code 3003.
  96. /// - error: The underlying error thrown by file manager.
  97. /// - key: The key used to getting the resource from cache.
  98. /// - url: The disk URL where the target cached file exists.
  99. case invalidURLResource(error: Error, key: String, url: URL)
  100. /// The file at target URL exists, but the data cannot be loaded from it. Code 3004.
  101. /// - url: The disk URL where the target cached file exists.
  102. /// - error: The underlying error which describes why this error happens.
  103. case cannotLoadDataFromDisk(url: URL, error: Error)
  104. /// Cannot create a folder at a given path. Code 3005.
  105. /// - path: The disk path where the directory creating operation fails.
  106. /// - error: The underlying error which describes why this error happens.
  107. case cannotCreateDirectory(path: String, error: Error)
  108. /// The requested image does not exist in cache. Code 3006.
  109. /// - key: Key of the requested image in cache.
  110. case imageNotExisting(key: String)
  111. /// Cannot convert an object to data for storing. Code 3007.
  112. /// - object: The object which needs be convert to data.
  113. case cannotConvertToData(object: Any, error: Error)
  114. /// Cannot serialize an image to data for storing. Code 3008.
  115. /// - image: The input image needs to be serialized to cache.
  116. /// - original: The original image data, if exists.
  117. /// - serializer: The `CacheSerializer` used for the image serializing.
  118. case cannotSerializeImage(image: KFCrossPlatformImage?, original: Data?, serializer: CacheSerializer)
  119. }
  120. /// Represents the error reason during image processing phase.
  121. ///
  122. /// - processingFailed: Image processing fails. There is no valid output image from the processor. Code 4001.
  123. public enum ProcessorErrorReason {
  124. /// Image processing fails. There is no valid output image from the processor. Code 4001.
  125. /// - processor: The `ImageProcessor` used to process the image or its data in `item`.
  126. /// - item: The image or its data content.
  127. case processingFailed(processor: ImageProcessor, item: ImageProcessItem)
  128. }
  129. /// Represents the error reason during image setting in a view related class.
  130. ///
  131. /// - emptySource: The input resource is empty or `nil`. Code 5001.
  132. /// - notCurrentSourceTask: The source task is finished, but it is not the one expected now. Code 5002.
  133. /// - dataProviderError: An error happens during getting data from an `ImageDataProvider`. Code 5003.
  134. public enum ImageSettingErrorReason {
  135. /// The input resource is empty or `nil`. Code 5001.
  136. case emptySource
  137. /// The resource task is finished, but it is not the one expected now. This usually happens when you set another
  138. /// resource on the view without cancelling the current on-going one. The previous setting task will fail with
  139. /// this `.notCurrentSourceTask` error when a result got, regardless of it being successful or not for that task.
  140. /// The result of this original task is contained in the associated value.
  141. /// Code 5002.
  142. /// - result: The `RetrieveImageResult` if the source task is finished without problem. `nil` if an error
  143. /// happens.
  144. /// - error: The `Error` if an issue happens during image setting task. `nil` if the task finishes without
  145. /// problem.
  146. /// - source: The original source value of the task.
  147. case notCurrentSourceTask(result: RetrieveImageResult?, error: Error?, source: Source)
  148. /// An error happens during getting data from an `ImageDataProvider`. Code 5003.
  149. case dataProviderError(provider: ImageDataProvider, error: Error)
  150. /// No more alternative `Source` can be used in current loading process. It means that the
  151. /// `.alternativeSources` are used and Kingfisher tried to recovery from the original error, but still
  152. /// fails for all the given alternative sources. The associated value holds all the errors encountered during
  153. /// the load process, including the original source loading error and all the alternative sources errors.
  154. /// Code 5004.
  155. case alternativeSourcesExhausted([PropagationError])
  156. }
  157. // MARK: Member Cases
  158. /// Represents the error reason during networking request phase.
  159. case requestError(reason: RequestErrorReason)
  160. /// Represents the error reason during networking response phase.
  161. case responseError(reason: ResponseErrorReason)
  162. /// Represents the error reason during Kingfisher caching system.
  163. case cacheError(reason: CacheErrorReason)
  164. /// Represents the error reason during image processing phase.
  165. case processorError(reason: ProcessorErrorReason)
  166. /// Represents the error reason during image setting in a view related class.
  167. case imageSettingError(reason: ImageSettingErrorReason)
  168. // MARK: Helper Properties & Methods
  169. /// Helper property to check whether this error is a `RequestErrorReason.taskCancelled` or not.
  170. public var isTaskCancelled: Bool {
  171. if case .requestError(reason: .taskCancelled) = self {
  172. return true
  173. }
  174. return false
  175. }
  176. /// Helper method to check whether this error is a `ResponseErrorReason.invalidHTTPStatusCode` and the
  177. /// associated value is a given status code.
  178. ///
  179. /// - Parameter code: The given status code.
  180. /// - Returns: If `self` is a `ResponseErrorReason.invalidHTTPStatusCode` error
  181. /// and its status code equals to `code`, `true` is returned. Otherwise, `false`.
  182. public func isInvalidResponseStatusCode(_ code: Int) -> Bool {
  183. if case .responseError(reason: .invalidHTTPStatusCode(let response)) = self {
  184. return response.statusCode == code
  185. }
  186. return false
  187. }
  188. public var isInvalidResponseStatusCode: Bool {
  189. if case .responseError(reason: .invalidHTTPStatusCode) = self {
  190. return true
  191. }
  192. return false
  193. }
  194. /// Helper property to check whether this error is a `ImageSettingErrorReason.notCurrentSourceTask` or not.
  195. /// When a new image setting task starts while the old one is still running, the new task identifier will be
  196. /// set and the old one is overwritten. A `.notCurrentSourceTask` error will be raised when the old task finishes
  197. /// to let you know the setting process finishes with a certain result, but the image view or button is not set.
  198. public var isNotCurrentTask: Bool {
  199. if case .imageSettingError(reason: .notCurrentSourceTask(_, _, _)) = self {
  200. return true
  201. }
  202. return false
  203. }
  204. }
  205. // MARK: - LocalizedError Conforming
  206. extension KingfisherError: LocalizedError {
  207. /// A localized message describing what error occurred.
  208. public var errorDescription: String? {
  209. switch self {
  210. case .requestError(let reason): return reason.errorDescription
  211. case .responseError(let reason): return reason.errorDescription
  212. case .cacheError(let reason): return reason.errorDescription
  213. case .processorError(let reason): return reason.errorDescription
  214. case .imageSettingError(let reason): return reason.errorDescription
  215. }
  216. }
  217. }
  218. // MARK: - CustomNSError Conforming
  219. extension KingfisherError: CustomNSError {
  220. /// The error domain of `KingfisherError`. All errors from Kingfisher is under this domain.
  221. public static let domain = "com.onevcat.Kingfisher.Error"
  222. /// The error code within the given domain.
  223. public var errorCode: Int {
  224. switch self {
  225. case .requestError(let reason): return reason.errorCode
  226. case .responseError(let reason): return reason.errorCode
  227. case .cacheError(let reason): return reason.errorCode
  228. case .processorError(let reason): return reason.errorCode
  229. case .imageSettingError(let reason): return reason.errorCode
  230. }
  231. }
  232. }
  233. extension KingfisherError.RequestErrorReason {
  234. var errorDescription: String? {
  235. switch self {
  236. case .emptyRequest:
  237. return "The request is empty or `nil`."
  238. case .invalidURL(let request):
  239. return "The request contains an invalid or empty URL. Request: \(request)."
  240. case .taskCancelled(let task, let token):
  241. return "The session task was cancelled. Task: \(task), cancel token: \(token)."
  242. }
  243. }
  244. var errorCode: Int {
  245. switch self {
  246. case .emptyRequest: return 1001
  247. case .invalidURL: return 1002
  248. case .taskCancelled: return 1003
  249. }
  250. }
  251. }
  252. extension KingfisherError.ResponseErrorReason {
  253. var errorDescription: String? {
  254. switch self {
  255. case .invalidURLResponse(let response):
  256. return "The URL response is invalid: \(response)"
  257. case .invalidHTTPStatusCode(let response):
  258. return "The HTTP status code in response is invalid. Code: \(response.statusCode), response: \(response)."
  259. case .URLSessionError(let error):
  260. return "A URL session error happened. The underlying error: \(error)"
  261. case .dataModifyingFailed(let task):
  262. return "The data modifying delegate returned `nil` for the downloaded data. Task: \(task)."
  263. case .noURLResponse(let task):
  264. return "No URL response received. Task: \(task),"
  265. }
  266. }
  267. var errorCode: Int {
  268. switch self {
  269. case .invalidURLResponse: return 2001
  270. case .invalidHTTPStatusCode: return 2002
  271. case .URLSessionError: return 2003
  272. case .dataModifyingFailed: return 2004
  273. case .noURLResponse: return 2005
  274. }
  275. }
  276. }
  277. extension KingfisherError.CacheErrorReason {
  278. var errorDescription: String? {
  279. switch self {
  280. case .fileEnumeratorCreationFailed(let url):
  281. return "Cannot create file enumerator for URL: \(url)."
  282. case .invalidFileEnumeratorContent(let url):
  283. return "Cannot get contents from the file enumerator at URL: \(url)."
  284. case .invalidURLResource(let error, let key, let url):
  285. return "Cannot get URL resource values or data for the given URL: \(url). " +
  286. "Cache key: \(key). Underlying error: \(error)"
  287. case .cannotLoadDataFromDisk(let url, let error):
  288. return "Cannot load data from disk at URL: \(url). Underlying error: \(error)"
  289. case .cannotCreateDirectory(let path, let error):
  290. return "Cannot create directory at given path: Path: \(path). Underlying error: \(error)"
  291. case .imageNotExisting(let key):
  292. return "The image is not in cache, but you requires it should only be " +
  293. "from cache by enabling the `.onlyFromCache` option. Key: \(key)."
  294. case .cannotConvertToData(let object, let error):
  295. return "Cannot convert the input object to a `Data` object when storing it to disk cache. " +
  296. "Object: \(object). Underlying error: \(error)"
  297. case .cannotSerializeImage(let image, let originalData, let serializer):
  298. return "Cannot serialize an image due to the cache serializer returning `nil`. " +
  299. "Image: \(String(describing:image)), original data: \(String(describing: originalData)), " +
  300. "serializer: \(serializer)."
  301. }
  302. }
  303. var errorCode: Int {
  304. switch self {
  305. case .fileEnumeratorCreationFailed: return 3001
  306. case .invalidFileEnumeratorContent: return 3002
  307. case .invalidURLResource: return 3003
  308. case .cannotLoadDataFromDisk: return 3004
  309. case .cannotCreateDirectory: return 3005
  310. case .imageNotExisting: return 3006
  311. case .cannotConvertToData: return 3007
  312. case .cannotSerializeImage: return 3008
  313. }
  314. }
  315. }
  316. extension KingfisherError.ProcessorErrorReason {
  317. var errorDescription: String? {
  318. switch self {
  319. case .processingFailed(let processor, let item):
  320. return "Processing image failed. Processor: \(processor). Processing item: \(item)."
  321. }
  322. }
  323. var errorCode: Int {
  324. switch self {
  325. case .processingFailed: return 4001
  326. }
  327. }
  328. }
  329. extension KingfisherError.ImageSettingErrorReason {
  330. var errorDescription: String? {
  331. switch self {
  332. case .emptySource:
  333. return "The input resource is empty."
  334. case .notCurrentSourceTask(let result, let error, let resource):
  335. if let result = result {
  336. return "Retrieving resource succeeded, but this source is " +
  337. "not the one currently expected. Result: \(result). Resource: \(resource)."
  338. } else if let error = error {
  339. return "Retrieving resource failed, and this resource is " +
  340. "not the one currently expected. Error: \(error). Resource: \(resource)."
  341. } else {
  342. return nil
  343. }
  344. case .dataProviderError(let provider, let error):
  345. return "Image data provider fails to provide data. Provider: \(provider), error: \(error)"
  346. case .alternativeSourcesExhausted(let errors):
  347. return "Image setting from alternaive sources failed: \(errors)"
  348. }
  349. }
  350. var errorCode: Int {
  351. switch self {
  352. case .emptySource: return 5001
  353. case .notCurrentSourceTask: return 5002
  354. case .dataProviderError: return 5003
  355. case .alternativeSourcesExhausted: return 5004
  356. }
  357. }
  358. }