KingfisherError.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. //
  2. // KingfisherError.swift
  3. // Kingfisher
  4. //
  5. // Created by onevcat on 2018/09/26.
  6. //
  7. // Copyright (c) 2018 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: Error {}
  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. /// The error domain of `KingfisherError`. All errors from Kingfisher is under this domain.
  34. public static let domain = "com.onevcat.Kingfisher.Error"
  35. /// Represents the error reason during networking request phase.
  36. ///
  37. /// - emptyRequest: The request is empty. Code 1001.
  38. /// - invalidURL: The URL of request is invalid. Code 1002.
  39. /// - taskCancelled: The downloading task is cancelled by user. Code 1003.
  40. public enum RequestErrorReason {
  41. /// The request is empty. Code 1001.
  42. case emptyRequest
  43. /// The URL of request is invalid. Code 1002.
  44. /// - request: The request is tend to be sent but its URL is invalid.
  45. case invalidURL(request: URLRequest)
  46. /// The downloading task is cancelled by user. Code 1003.
  47. /// - task: The session data task which is cancelled.
  48. /// - token: The cancel token which is used for cancelling the task.
  49. case taskCancelled(task: SessionDataTask, token: SessionDataTask.CancelToken)
  50. }
  51. /// Represents the error reason during networking response phase.
  52. ///
  53. /// - invalidURLResponse: The response is not a valid URL response. Code 2001.
  54. /// - invalidHTTPStatusCode: The response contains an invalid HTTP status code. Code 2002.
  55. /// - URLSessionError: An error happens in the system URL session. Code 2003.
  56. /// - dataModifyingFailed: Data modifying fails on returning a valid data. Code 2004.
  57. /// - noURLResponse: The task is done but no URL response found. Code 2005.
  58. public enum ResponseErrorReason {
  59. /// The response is not a valid URL response. Code 2001.
  60. /// - response: The received invalid URL response.
  61. /// The response is expected to be an HTTP response, but it is not.
  62. case invalidURLResponse(response: URLResponse)
  63. /// The response contains an invalid HTTP status code. Code 2002.
  64. /// - Note:
  65. /// By default, status code 200..<400 is recognized as valid. You can override
  66. /// this behavior by conforming to the `ImageDownloaderDelegate`.
  67. /// - response: The received response.
  68. case invalidHTTPStatusCode(response: HTTPURLResponse)
  69. /// An error happens in the system URL session. Code 2003.
  70. /// - error: The underlying URLSession error object.
  71. case URLSessionError(error: Error)
  72. /// Data modifying fails on returning a valid data. Code 2004.
  73. /// - task: The failed task.
  74. case dataModifyingFailed(task: SessionDataTask)
  75. /// The task is done but no URL response found. Code 2005.
  76. /// - task: The failed task.
  77. case noURLResponse(task: SessionDataTask)
  78. }
  79. /// Represents the error reason during Kingfisher caching system.
  80. ///
  81. /// - fileEnumeratorCreationFailed: Cannot create a file enumerator for a certain disk URL. Code 3001.
  82. /// - invalidFileEnumeratorContent: Cannot get correct file contents from a file enumerator. Code 3002.
  83. /// - invalidURLResource: The file at target URL exists, but its URL resource is unavailable. Code 3003.
  84. /// - cannotLoadDataFromDisk: The file at target URL exists, but the data cannot be loaded from it. Code 3004.
  85. /// - cannotCreateDirectory: Cannot create a folder at a given path. Code 3005.
  86. /// - imageNotExisting: The requested image does not exist in cache. Code 3006.
  87. /// - cannotConvertToData: Cannot convert an object to data for storing. Code 3007.
  88. /// - cannotSerializeImage: Cannot serialize an image to data for storing. Code 3008.
  89. public enum CacheErrorReason {
  90. /// Cannot create a file enumerator for a certain disk URL. Code 3001.
  91. /// - url: The target disk URL from which the file enumerator should be created.
  92. case fileEnumeratorCreationFailed(url: URL)
  93. /// Cannot get correct file contents from a file enumerator. Code 3002.
  94. /// - url: The target disk URL from which the content of a file enumerator should be got.
  95. case invalidFileEnumeratorContent(url: URL)
  96. /// The file at target URL exists, but its URL resource is unavailable. Code 3003.
  97. /// - error: The underlying error thrown by file manager.
  98. /// - key: The key used to getting the resource from cache.
  99. /// - url: The disk URL where the target cached file exists.
  100. case invalidURLResource(error: Error, key: String, url: URL)
  101. /// The file at target URL exists, but the data cannot be loaded from it. Code 3004.
  102. /// - url: The disk URL where the target cached file exists.
  103. /// - error: The underlying error which describes why this error happens.
  104. case cannotLoadDataFromDisk(url: URL, error: Error)
  105. /// Cannot create a folder at a given path. Code 3005.
  106. /// - path: The disk path where the directory creating operation fails.
  107. /// - error: The underlying error which describes why this error happens.
  108. case cannotCreateDirectory(path: String, error: Error)
  109. /// The requested image does not exist in cache. Code 3006.
  110. /// - key: Key of the requested image in cache.
  111. case imageNotExisting(key: String)
  112. /// Cannot convert an object to data for storing. Code 3007.
  113. /// - object: The object which needs be convert to data.
  114. case cannotConvertToData(object: Any, error: Error)
  115. /// Cannot serialize an image to data for storing. Code 3008.
  116. /// - image: The input image needs to be serialized to cache.
  117. /// - original: The original image data, if exists.
  118. /// - serializer: The `CacheSerializer` used for the image serializing.
  119. case cannotSerializeImage(image: Image?, original: Data?, serializer: CacheSerializer)
  120. }
  121. /// Represents the error reason during image processing phase.
  122. ///
  123. /// - processingFailed: Image processing fails. There is no valid output image from the processor. Code 4001.
  124. public enum ProcessorErrorReason {
  125. /// Image processing fails. There is no valid output image from the processor. Code 4001.
  126. /// - processor: The `ImageProcessor` used to process the image or its data in `item`.
  127. /// - item: The image or its data content.
  128. case processingFailed(processor: ImageProcessor, item: ImageProcessItem)
  129. }
  130. /// Represents the error reason during image setting in a view related class.
  131. ///
  132. /// - emptySource: The input resource is empty or `nil`. Code 5001.
  133. /// - notCurrentSourceTask: The source task is finished, but it is not the one expected now. Code 5002.
  134. /// - dataProviderError: An error happens during getting data from an `ImageDataProvider`. Code 5003.
  135. public enum ImageSettingErrorReason {
  136. /// The input resource is empty or `nil`. Code 5001.
  137. case emptySource
  138. /// The resource task is finished, but it is not the one expected now. This usually happens when you set another
  139. /// resource on the view without cancelling the current on-going one. The previous setting task will fail with
  140. /// this `.notCurrentSourceTask` error when a result got, regardless of it being successful or not for that task.
  141. /// The result of this original task is contained in the associated value.
  142. /// Code 5002.
  143. /// - result: The `RetrieveImageResult` if the source task is finished without problem. `nil` if an error
  144. /// happens.
  145. /// - error: The `Error` if an issue happens during image setting task. `nil` if the task finishes without
  146. /// problem.
  147. /// - source: The original source value of the taks.
  148. case notCurrentSourceTask(result: RetrieveImageResult?, error: Error?, source: Source)
  149. /// An error happens during getting data from an `ImageDataProvider`. Code 5003.
  150. case dataProviderError(provider: ImageDataProvider, error: Error)
  151. }
  152. /// Represents the error reason during networking request phase.
  153. case requestError(reason: RequestErrorReason)
  154. /// Represents the error reason during networking response phase.
  155. case responseError(reason: ResponseErrorReason)
  156. /// Represents the error reason during Kingfisher caching system.
  157. case cacheError(reason: CacheErrorReason)
  158. /// Represents the error reason during image processing phase.
  159. case processorError(reason: ProcessorErrorReason)
  160. /// Represents the error reason during image setting in a view related class.
  161. case imageSettingError(reason: ImageSettingErrorReason)
  162. /// Helper property to check whether this error is a `RequestErrorReason.taskCancelled` or not.
  163. public var isTaskCancelled: Bool {
  164. if case .requestError(reason: .taskCancelled) = self {
  165. return true
  166. }
  167. return false
  168. }
  169. /// Helper method to check whether this error is a `ResponseErrorReason.invalidHTTPStatusCode` and the
  170. /// associated value is a given status code.
  171. ///
  172. /// - Parameter code: The given status code.
  173. /// - Returns: If `self` is a `ResponseErrorReason.invalidHTTPStatusCode` error
  174. /// and its status code equals to `code`, `true` is returned. Otherwise, `false`.
  175. public func isInvalidResponseStatusCode(_ code: Int) -> Bool {
  176. if case .responseError(reason: .invalidHTTPStatusCode(let response)) = self {
  177. return response.statusCode == code
  178. }
  179. return false
  180. }
  181. public var isInvalidResponseStatusCode: Bool {
  182. if case .responseError(reason: .invalidHTTPStatusCode) = self {
  183. return true
  184. }
  185. return false
  186. }
  187. /// Helper property to check whether this error is a `ImageSettingErrorReason.notCurrentSourceTask` or not.
  188. /// When a new image setting task starts while the old one is still running, the new task identifier will be
  189. /// set and the old one is overwritten. A `.notCurrentSourceTask` error will be raised when the old task finishes
  190. /// to let you know the setting process finishes with a certain result, but the image view or button is not set.
  191. public var isNotCurrentTask: Bool {
  192. if case .imageSettingError(reason: .notCurrentSourceTask(_, _, _)) = self {
  193. return true
  194. }
  195. return false
  196. }
  197. }
  198. extension KingfisherError: LocalizedError {
  199. /// A localized message describing what error occurred.
  200. public var errorDescription: String? {
  201. switch self {
  202. case .requestError(let reason): return reason.errorDescription
  203. case .responseError(let reason): return reason.errorDescription
  204. case .cacheError(let reason): return reason.errorDescription
  205. case .processorError(let reason): return reason.errorDescription
  206. case .imageSettingError(let reason): return reason.errorDescription
  207. }
  208. }
  209. }
  210. extension KingfisherError: CustomNSError {
  211. /// The error code within the given domain.
  212. public var errorCode: Int {
  213. switch self {
  214. case .requestError(let reason): return reason.errorCode
  215. case .responseError(let reason): return reason.errorCode
  216. case .cacheError(let reason): return reason.errorCode
  217. case .processorError(let reason): return reason.errorCode
  218. case .imageSettingError(let reason): return reason.errorCode
  219. }
  220. }
  221. }
  222. extension KingfisherError.RequestErrorReason {
  223. var errorDescription: String? {
  224. switch self {
  225. case .emptyRequest:
  226. return "The request is empty or `nil`."
  227. case .invalidURL(let request):
  228. return "The request contains an invalid or empty URL. Request: \(request)."
  229. case .taskCancelled(let task, let token):
  230. return "The session task was cancelled. Task: \(task), cancel token: \(token)."
  231. }
  232. }
  233. var errorCode: Int {
  234. switch self {
  235. case .emptyRequest: return 1001
  236. case .invalidURL: return 1002
  237. case .taskCancelled: return 1003
  238. }
  239. }
  240. }
  241. extension KingfisherError.ResponseErrorReason {
  242. var errorDescription: String? {
  243. switch self {
  244. case .invalidURLResponse(let response):
  245. return "The URL response is invalid: \(response)"
  246. case .invalidHTTPStatusCode(let response):
  247. return "The HTTP status code in response is invalid. Code: \(response.statusCode), response: \(response)."
  248. case .URLSessionError(let error):
  249. return "A URL session error happened. The underlying error: \(error)"
  250. case .dataModifyingFailed(let task):
  251. return "The data modifying delegate returned `nil` for the downloaded data. Task: \(task)."
  252. case .noURLResponse(let task):
  253. return "No URL response received. Task: \(task),"
  254. }
  255. }
  256. var errorCode: Int {
  257. switch self {
  258. case .invalidURLResponse: return 2001
  259. case .invalidHTTPStatusCode: return 2002
  260. case .URLSessionError: return 2003
  261. case .dataModifyingFailed: return 2004
  262. case .noURLResponse: return 2005
  263. }
  264. }
  265. }
  266. extension KingfisherError.CacheErrorReason {
  267. var errorDescription: String? {
  268. switch self {
  269. case .fileEnumeratorCreationFailed(let url):
  270. return "Cannot create file enumerator for URL: \(url)."
  271. case .invalidFileEnumeratorContent(let url):
  272. return "Cannot get contents from the file enumerator at URL: \(url)."
  273. case .invalidURLResource(let error, let key, let url):
  274. return "Cannot get URL resource values or data for the given URL: \(url). " +
  275. "Cache key: \(key). Underlying error: \(error)"
  276. case .cannotLoadDataFromDisk(let url, let error):
  277. return "Cannot load data from disk at URL: \(url). Underlying error: \(error)"
  278. case .cannotCreateDirectory(let path, let error):
  279. return "Cannot create directory at given path: Path: \(path). Underlying error: \(error)"
  280. case .imageNotExisting(let key):
  281. return "The image is not in cache, but you requires it should only be " +
  282. "from cache by enabling the `.onlyFromCache` option. Key: \(key)."
  283. case .cannotConvertToData(let object, let error):
  284. return "Cannot convert the input object to a `Data` object when storing it to disk cache. " +
  285. "Object: \(object). Underlying error: \(error)"
  286. case .cannotSerializeImage(let image, let originalData, let serializer):
  287. return "Cannot serialize an image due to the cache serializer returning `nil`. " +
  288. "Image: \(String(describing:image)), original data: \(String(describing: originalData)), serializer: \(serializer)."
  289. }
  290. }
  291. var errorCode: Int {
  292. switch self {
  293. case .fileEnumeratorCreationFailed: return 3001
  294. case .invalidFileEnumeratorContent: return 3002
  295. case .invalidURLResource: return 3003
  296. case .cannotLoadDataFromDisk: return 3004
  297. case .cannotCreateDirectory: return 3005
  298. case .imageNotExisting: return 3006
  299. case .cannotConvertToData: return 3007
  300. case .cannotSerializeImage: return 3008
  301. }
  302. }
  303. }
  304. extension KingfisherError.ProcessorErrorReason {
  305. var errorDescription: String? {
  306. switch self {
  307. case .processingFailed(let processor, let item):
  308. return "Processing image failed. Processor: \(processor). Processing item: \(item)."
  309. }
  310. }
  311. var errorCode: Int {
  312. switch self {
  313. case .processingFailed: return 4001
  314. }
  315. }
  316. }
  317. extension KingfisherError.ImageSettingErrorReason {
  318. var errorDescription: String? {
  319. switch self {
  320. case .emptySource:
  321. return "The input resource is empty."
  322. case .notCurrentSourceTask(let result, let error, let resource):
  323. if let result = result {
  324. return "Retrieving resource succeeded, but this source is " +
  325. "not the one currently expected. Result: \(result). Resource: \(resource)."
  326. } else if let error = error {
  327. return "Retrieving resource failed, and this resource is " +
  328. "not the one currently expected. Error: \(error). Resource: \(resource)."
  329. } else {
  330. return nil
  331. }
  332. case .dataProviderError(let provider, let error):
  333. return "Image data provider fails to provide data. Provider: \(provider), error: \(error)"
  334. }
  335. }
  336. var errorCode: Int {
  337. switch self {
  338. case .emptySource: return 5001
  339. case .notCurrentSourceTask: return 5002
  340. case .dataProviderError: return 5003
  341. }
  342. }
  343. }