You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

437 lines
21 KiB

  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. /// - cannotCreateCacheFile: Cannot create the cache file at a certain fileURL under a key. Code 3009.
  89. /// - cannotSetCacheFileAttribute: Cannot set file attributes to a cached file. Code 3010.
  90. public enum CacheErrorReason {
  91. /// Cannot create a file enumerator for a certain disk URL. Code 3001.
  92. /// - url: The target disk URL from which the file enumerator should be created.
  93. case fileEnumeratorCreationFailed(url: URL)
  94. /// Cannot get correct file contents from a file enumerator. Code 3002.
  95. /// - url: The target disk URL from which the content of a file enumerator should be got.
  96. case invalidFileEnumeratorContent(url: URL)
  97. /// The file at target URL exists, but its URL resource is unavailable. Code 3003.
  98. /// - error: The underlying error thrown by file manager.
  99. /// - key: The key used to getting the resource from cache.
  100. /// - url: The disk URL where the target cached file exists.
  101. case invalidURLResource(error: Error, key: String, url: URL)
  102. /// The file at target URL exists, but the data cannot be loaded from it. Code 3004.
  103. /// - url: The disk URL where the target cached file exists.
  104. /// - error: The underlying error which describes why this error happens.
  105. case cannotLoadDataFromDisk(url: URL, error: Error)
  106. /// Cannot create a folder at a given path. Code 3005.
  107. /// - path: The disk path where the directory creating operation fails.
  108. /// - error: The underlying error which describes why this error happens.
  109. case cannotCreateDirectory(path: String, error: Error)
  110. /// The requested image does not exist in cache. Code 3006.
  111. /// - key: Key of the requested image in cache.
  112. case imageNotExisting(key: String)
  113. /// Cannot convert an object to data for storing. Code 3007.
  114. /// - object: The object which needs be convert to data.
  115. case cannotConvertToData(object: Any, error: Error)
  116. /// Cannot serialize an image to data for storing. Code 3008.
  117. /// - image: The input image needs to be serialized to cache.
  118. /// - original: The original image data, if exists.
  119. /// - serializer: The `CacheSerializer` used for the image serializing.
  120. case cannotSerializeImage(image: KFCrossPlatformImage?, original: Data?, serializer: CacheSerializer)
  121. /// Cannot create the cache file at a certain fileURL under a key. Code 3009.
  122. /// - fileURL: The url where the cache file should be created.
  123. /// - key: The cache key used for the cache. When caching a file through `KingfisherManager` and Kingfisher's
  124. /// extension method, it is the resolved cache key based on your input `Source` and the image processors.
  125. /// - data: The data to be cached.
  126. /// - error: The underlying error originally thrown by Foundation when writing the `data` to the disk file at
  127. /// `fileURL`.
  128. case cannotCreateCacheFile(fileURL: URL, key: String, data: Data, error: Error)
  129. /// Cannot set file attributes to a cached file. Code 3010.
  130. /// - filePath: The path of target cache file.
  131. /// - attributes: The file attribute to be set to the target file.
  132. /// - error: The underlying error originally thrown by Foundation when setting the `attributes` to the disk
  133. /// file at `filePath`.
  134. case cannotSetCacheFileAttribute(filePath: String, attributes: [FileAttributeKey : Any], error: Error)
  135. }
  136. /// Represents the error reason during image processing phase.
  137. ///
  138. /// - processingFailed: Image processing fails. There is no valid output image from the processor. Code 4001.
  139. public enum ProcessorErrorReason {
  140. /// Image processing fails. There is no valid output image from the processor. Code 4001.
  141. /// - processor: The `ImageProcessor` used to process the image or its data in `item`.
  142. /// - item: The image or its data content.
  143. case processingFailed(processor: ImageProcessor, item: ImageProcessItem)
  144. }
  145. /// Represents the error reason during image setting in a view related class.
  146. ///
  147. /// - emptySource: The input resource is empty or `nil`. Code 5001.
  148. /// - notCurrentSourceTask: The source task is finished, but it is not the one expected now. Code 5002.
  149. /// - dataProviderError: An error happens during getting data from an `ImageDataProvider`. Code 5003.
  150. public enum ImageSettingErrorReason {
  151. /// The input resource is empty or `nil`. Code 5001.
  152. case emptySource
  153. /// The resource task is finished, but it is not the one expected now. This usually happens when you set another
  154. /// resource on the view without cancelling the current on-going one. The previous setting task will fail with
  155. /// this `.notCurrentSourceTask` error when a result got, regardless of it being successful or not for that task.
  156. /// The result of this original task is contained in the associated value.
  157. /// Code 5002.
  158. /// - result: The `RetrieveImageResult` if the source task is finished without problem. `nil` if an error
  159. /// happens.
  160. /// - error: The `Error` if an issue happens during image setting task. `nil` if the task finishes without
  161. /// problem.
  162. /// - source: The original source value of the task.
  163. case notCurrentSourceTask(result: RetrieveImageResult?, error: Error?, source: Source)
  164. /// An error happens during getting data from an `ImageDataProvider`. Code 5003.
  165. case dataProviderError(provider: ImageDataProvider, error: Error)
  166. /// No more alternative `Source` can be used in current loading process. It means that the
  167. /// `.alternativeSources` are used and Kingfisher tried to recovery from the original error, but still
  168. /// fails for all the given alternative sources. The associated value holds all the errors encountered during
  169. /// the load process, including the original source loading error and all the alternative sources errors.
  170. /// Code 5004.
  171. case alternativeSourcesExhausted([PropagationError])
  172. }
  173. // MARK: Member Cases
  174. /// Represents the error reason during networking request phase.
  175. case requestError(reason: RequestErrorReason)
  176. /// Represents the error reason during networking response phase.
  177. case responseError(reason: ResponseErrorReason)
  178. /// Represents the error reason during Kingfisher caching system.
  179. case cacheError(reason: CacheErrorReason)
  180. /// Represents the error reason during image processing phase.
  181. case processorError(reason: ProcessorErrorReason)
  182. /// Represents the error reason during image setting in a view related class.
  183. case imageSettingError(reason: ImageSettingErrorReason)
  184. // MARK: Helper Properties & Methods
  185. /// Helper property to check whether this error is a `RequestErrorReason.taskCancelled` or not.
  186. public var isTaskCancelled: Bool {
  187. if case .requestError(reason: .taskCancelled) = self {
  188. return true
  189. }
  190. return false
  191. }
  192. /// Helper method to check whether this error is a `ResponseErrorReason.invalidHTTPStatusCode` and the
  193. /// associated value is a given status code.
  194. ///
  195. /// - Parameter code: The given status code.
  196. /// - Returns: If `self` is a `ResponseErrorReason.invalidHTTPStatusCode` error
  197. /// and its status code equals to `code`, `true` is returned. Otherwise, `false`.
  198. public func isInvalidResponseStatusCode(_ code: Int) -> Bool {
  199. if case .responseError(reason: .invalidHTTPStatusCode(let response)) = self {
  200. return response.statusCode == code
  201. }
  202. return false
  203. }
  204. public var isInvalidResponseStatusCode: Bool {
  205. if case .responseError(reason: .invalidHTTPStatusCode) = self {
  206. return true
  207. }
  208. return false
  209. }
  210. /// Helper property to check whether this error is a `ImageSettingErrorReason.notCurrentSourceTask` or not.
  211. /// When a new image setting task starts while the old one is still running, the new task identifier will be
  212. /// set and the old one is overwritten. A `.notCurrentSourceTask` error will be raised when the old task finishes
  213. /// to let you know the setting process finishes with a certain result, but the image view or button is not set.
  214. public var isNotCurrentTask: Bool {
  215. if case .imageSettingError(reason: .notCurrentSourceTask(_, _, _)) = self {
  216. return true
  217. }
  218. return false
  219. }
  220. }
  221. // MARK: - LocalizedError Conforming
  222. extension KingfisherError: LocalizedError {
  223. /// A localized message describing what error occurred.
  224. public var errorDescription: String? {
  225. switch self {
  226. case .requestError(let reason): return reason.errorDescription
  227. case .responseError(let reason): return reason.errorDescription
  228. case .cacheError(let reason): return reason.errorDescription
  229. case .processorError(let reason): return reason.errorDescription
  230. case .imageSettingError(let reason): return reason.errorDescription
  231. }
  232. }
  233. }
  234. // MARK: - CustomNSError Conforming
  235. extension KingfisherError: CustomNSError {
  236. /// The error domain of `KingfisherError`. All errors from Kingfisher is under this domain.
  237. public static let domain = "com.onevcat.Kingfisher.Error"
  238. /// The error code within the given domain.
  239. public var errorCode: Int {
  240. switch self {
  241. case .requestError(let reason): return reason.errorCode
  242. case .responseError(let reason): return reason.errorCode
  243. case .cacheError(let reason): return reason.errorCode
  244. case .processorError(let reason): return reason.errorCode
  245. case .imageSettingError(let reason): return reason.errorCode
  246. }
  247. }
  248. }
  249. extension KingfisherError.RequestErrorReason {
  250. var errorDescription: String? {
  251. switch self {
  252. case .emptyRequest:
  253. return "The request is empty or `nil`."
  254. case .invalidURL(let request):
  255. return "The request contains an invalid or empty URL. Request: \(request)."
  256. case .taskCancelled(let task, let token):
  257. return "The session task was cancelled. Task: \(task), cancel token: \(token)."
  258. }
  259. }
  260. var errorCode: Int {
  261. switch self {
  262. case .emptyRequest: return 1001
  263. case .invalidURL: return 1002
  264. case .taskCancelled: return 1003
  265. }
  266. }
  267. }
  268. extension KingfisherError.ResponseErrorReason {
  269. var errorDescription: String? {
  270. switch self {
  271. case .invalidURLResponse(let response):
  272. return "The URL response is invalid: \(response)"
  273. case .invalidHTTPStatusCode(let response):
  274. return "The HTTP status code in response is invalid. Code: \(response.statusCode), response: \(response)."
  275. case .URLSessionError(let error):
  276. return "A URL session error happened. The underlying error: \(error)"
  277. case .dataModifyingFailed(let task):
  278. return "The data modifying delegate returned `nil` for the downloaded data. Task: \(task)."
  279. case .noURLResponse(let task):
  280. return "No URL response received. Task: \(task),"
  281. }
  282. }
  283. var errorCode: Int {
  284. switch self {
  285. case .invalidURLResponse: return 2001
  286. case .invalidHTTPStatusCode: return 2002
  287. case .URLSessionError: return 2003
  288. case .dataModifyingFailed: return 2004
  289. case .noURLResponse: return 2005
  290. }
  291. }
  292. }
  293. extension KingfisherError.CacheErrorReason {
  294. var errorDescription: String? {
  295. switch self {
  296. case .fileEnumeratorCreationFailed(let url):
  297. return "Cannot create file enumerator for URL: \(url)."
  298. case .invalidFileEnumeratorContent(let url):
  299. return "Cannot get contents from the file enumerator at URL: \(url)."
  300. case .invalidURLResource(let error, let key, let url):
  301. return "Cannot get URL resource values or data for the given URL: \(url). " +
  302. "Cache key: \(key). Underlying error: \(error)"
  303. case .cannotLoadDataFromDisk(let url, let error):
  304. return "Cannot load data from disk at URL: \(url). Underlying error: \(error)"
  305. case .cannotCreateDirectory(let path, let error):
  306. return "Cannot create directory at given path: Path: \(path). Underlying error: \(error)"
  307. case .imageNotExisting(let key):
  308. return "The image is not in cache, but you requires it should only be " +
  309. "from cache by enabling the `.onlyFromCache` option. Key: \(key)."
  310. case .cannotConvertToData(let object, let error):
  311. return "Cannot convert the input object to a `Data` object when storing it to disk cache. " +
  312. "Object: \(object). Underlying error: \(error)"
  313. case .cannotSerializeImage(let image, let originalData, let serializer):
  314. return "Cannot serialize an image due to the cache serializer returning `nil`. " +
  315. "Image: \(String(describing:image)), original data: \(String(describing: originalData)), " +
  316. "serializer: \(serializer)."
  317. case .cannotCreateCacheFile(let fileURL, let key, let data, let error):
  318. return "Cannot create cache file at url: \(fileURL), key: \(key), data length: \(data.count). " +
  319. "Underlying foundation error: \(error)."
  320. case .cannotSetCacheFileAttribute(let filePath, let attributes, let error):
  321. return "Cannot set file attribute for the cache file at path: \(filePath), attributes: \(attributes)." +
  322. "Underlying foundation error: \(error)."
  323. }
  324. }
  325. var errorCode: Int {
  326. switch self {
  327. case .fileEnumeratorCreationFailed: return 3001
  328. case .invalidFileEnumeratorContent: return 3002
  329. case .invalidURLResource: return 3003
  330. case .cannotLoadDataFromDisk: return 3004
  331. case .cannotCreateDirectory: return 3005
  332. case .imageNotExisting: return 3006
  333. case .cannotConvertToData: return 3007
  334. case .cannotSerializeImage: return 3008
  335. case .cannotCreateCacheFile: return 3009
  336. case .cannotSetCacheFileAttribute: return 3010
  337. }
  338. }
  339. }
  340. extension KingfisherError.ProcessorErrorReason {
  341. var errorDescription: String? {
  342. switch self {
  343. case .processingFailed(let processor, let item):
  344. return "Processing image failed. Processor: \(processor). Processing item: \(item)."
  345. }
  346. }
  347. var errorCode: Int {
  348. switch self {
  349. case .processingFailed: return 4001
  350. }
  351. }
  352. }
  353. extension KingfisherError.ImageSettingErrorReason {
  354. var errorDescription: String? {
  355. switch self {
  356. case .emptySource:
  357. return "The input resource is empty."
  358. case .notCurrentSourceTask(let result, let error, let resource):
  359. if let result = result {
  360. return "Retrieving resource succeeded, but this source is " +
  361. "not the one currently expected. Result: \(result). Resource: \(resource)."
  362. } else if let error = error {
  363. return "Retrieving resource failed, and this resource is " +
  364. "not the one currently expected. Error: \(error). Resource: \(resource)."
  365. } else {
  366. return nil
  367. }
  368. case .dataProviderError(let provider, let error):
  369. return "Image data provider fails to provide data. Provider: \(provider), error: \(error)"
  370. case .alternativeSourcesExhausted(let errors):
  371. return "Image setting from alternaive sources failed: \(errors)"
  372. }
  373. }
  374. var errorCode: Int {
  375. switch self {
  376. case .emptySource: return 5001
  377. case .notCurrentSourceTask: return 5002
  378. case .dataProviderError: return 5003
  379. case .alternativeSourcesExhausted: return 5004
  380. }
  381. }
  382. }