KingfisherError.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  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. #if os(macOS)
  28. import AppKit
  29. #else
  30. import UIKit
  31. #endif
  32. extension Never {}
  33. /// Represents all the errors that can occur in the Kingfisher framework.
  34. ///
  35. /// Kingfisher-related methods always throw a ``KingfisherError`` or invoke the callback with ``KingfisherError``
  36. /// as its error type. To handle errors from Kingfisher, you switch over the error to get a reason catalog,
  37. /// then switch over the reason to understand the error details.
  38. ///
  39. public enum KingfisherError: Error {
  40. // MARK: Error Reason Types
  41. /// Represents the error reasons during the networking request phase.
  42. public enum RequestErrorReason: Sendable {
  43. /// The request is empty.
  44. ///
  45. /// Error Code: 1001
  46. case emptyRequest
  47. /// The URL of the request is invalid.
  48. ///
  49. /// - Parameter request: The request is intended to be sent, but its URL is invalid.
  50. ///
  51. /// Error Code: 1002
  52. case invalidURL(request: URLRequest)
  53. /// The downloading task is canceled by the user.
  54. ///
  55. /// - Parameters:
  56. /// - task: The session data task which is canceled.
  57. /// - token: The cancel token which is used for canceling the task.
  58. ///
  59. /// Error Code: 1003
  60. case taskCancelled(task: SessionDataTask, token: SessionDataTask.CancelToken)
  61. /// The live photo downloading task is canceled by the user.
  62. ///
  63. /// - Parameters:
  64. /// - source: The live phot source.
  65. ///
  66. /// Error Code: 1004
  67. case livePhotoTaskCancelled(source: LivePhotoSource)
  68. }
  69. /// Represents the error reason during networking response phase.
  70. public enum ResponseErrorReason: Sendable {
  71. /// The response is not a valid URL response.
  72. ///
  73. /// - Parameters:
  74. /// - response: The received invalid URL response.
  75. /// The response is expected to be an HTTP response, but it is not.
  76. ///
  77. /// Error Code: 2001
  78. case invalidURLResponse(response: URLResponse)
  79. /// The response contains an invalid HTTP status code.
  80. ///
  81. /// - Parameters:
  82. /// - response: The received response.
  83. ///
  84. /// Error Code: 2002
  85. ///
  86. /// - Note: By default, status code 200..<400 is recognized as valid. You can override
  87. /// this behavior by conforming to the `ImageDownloaderDelegate`.
  88. case invalidHTTPStatusCode(response: HTTPURLResponse)
  89. /// An error happens in the system URL session.
  90. ///
  91. /// - Parameters:
  92. /// - error: The underlying URLSession error object.
  93. ///
  94. /// Error Code: 2003
  95. case URLSessionError(error: any Error)
  96. /// Data modifying fails on returning a valid data.
  97. ///
  98. /// - Parameters:
  99. /// - task: The failed task.
  100. ///
  101. /// Error Code: 2004
  102. case dataModifyingFailed(task: SessionDataTask)
  103. /// The task is done but no URL response found.
  104. ///
  105. /// - Parameters:
  106. /// - task: The failed task.
  107. ///
  108. /// Error Code: 2005
  109. case noURLResponse(task: SessionDataTask)
  110. /// The task is cancelled by ``ImageDownloaderDelegate`` due to the `.cancel` response disposition is
  111. /// specified by the delegate method.
  112. ///
  113. /// - Parameters:
  114. /// - task: The cancelled task.
  115. ///
  116. /// Error Code: 2006
  117. case cancelledByDelegate(response: URLResponse)
  118. }
  119. /// Represents the error reason during Kingfisher caching.
  120. public enum CacheErrorReason: @unchecked Sendable {
  121. /// Cannot create a file enumerator for a certain disk URL.
  122. ///
  123. /// - Parameters:
  124. /// - url: The target disk URL from which the file enumerator should be created.
  125. ///
  126. /// Error Code: 3001
  127. case fileEnumeratorCreationFailed(url: URL)
  128. /// Cannot get correct file contents from a file enumerator.
  129. ///
  130. /// - Parameters:
  131. /// - url: The target disk URL from which the content of a file enumerator should be obtained.
  132. ///
  133. /// Error Code: 3002
  134. case invalidFileEnumeratorContent(url: URL)
  135. /// The file at the target URL exists, but its URL resource is unavailable.
  136. ///
  137. /// - Parameters:
  138. /// - error: The underlying error thrown by the file manager.
  139. /// - key: The key used to retrieve the resource from cache.
  140. /// - url: The disk URL where the target cached file exists.
  141. ///
  142. /// Error Code: 3003
  143. case invalidURLResource(error: any Error, key: String, url: URL)
  144. /// The file at the target URL exists, but the data cannot be loaded from it.
  145. ///
  146. /// - Parameters:
  147. /// - url: The disk URL where the target cached file exists.
  148. /// - error: The underlying error that describes why this error occurs.
  149. ///
  150. /// Error Code: 3004
  151. case cannotLoadDataFromDisk(url: URL, error: any Error)
  152. /// Cannot create a folder at a given path.
  153. ///
  154. /// - Parameters:
  155. /// - path: The disk path where the directory creation operation fails.
  156. /// - error: The underlying error that describes why this error occurs.
  157. ///
  158. /// Error Code: 3005
  159. case cannotCreateDirectory(path: String, error: any Error)
  160. /// The requested image does not exist in the cache.
  161. ///
  162. /// - Parameters:
  163. /// - key: The key of the requested image in the cache.
  164. ///
  165. /// Error Code: 3006
  166. case imageNotExisting(key: String)
  167. /// Unable to convert an object to data for storage.
  168. ///
  169. /// - Parameters:
  170. /// - object: The object that needs to be converted to data.
  171. ///
  172. /// Error Code: 3007
  173. case cannotConvertToData(object: Any, error: any Error)
  174. /// Unable to serialize an image to data for storage.
  175. ///
  176. /// - Parameters:
  177. /// - image: The input image that needs to be serialized to cache.
  178. /// - original: The original image data, if it exists.
  179. /// - serializer: The ``CacheSerializer`` used for the image serialization.
  180. ///
  181. /// Error Code: 3008
  182. case cannotSerializeImage(image: KFCrossPlatformImage?, original: Data?, serializer: any CacheSerializer)
  183. /// Unable to create the cache file at a specified `fileURL` under a given `key`.
  184. ///
  185. /// - Parameters:
  186. /// - fileURL: The URL where the cache file should be created.
  187. /// - key: The cache key used for the cache. When caching a file through ``KingfisherManager`` and Kingfisher's
  188. /// extension method, it is the resolved cache key based on your input ``Source`` and the image
  189. /// processors.
  190. /// - data: The data to be cached.
  191. /// - error: The underlying error originally thrown by Foundation when attempting to write the `data` to the disk file at
  192. /// `fileURL`.
  193. ///
  194. /// Error Code: 3009
  195. case cannotCreateCacheFile(fileURL: URL, key: String, data: Data, error: any Error)
  196. /// Unable to set file attributes for a cached file.
  197. ///
  198. /// - Parameters:
  199. /// - filePath: The path of the target cache file.
  200. /// - attributes: The file attributes to be set for the target file.
  201. /// - error: The underlying error originally thrown by the Foundation framework when attempting to set the specified
  202. /// `attributes` for the disk file at `filePath`.
  203. ///
  204. /// Error Code: 3010
  205. case cannotSetCacheFileAttribute(filePath: String, attributes: [FileAttributeKey : Any], error: any Error)
  206. /// The disk storage for caching is not ready.
  207. ///
  208. /// - Parameters:
  209. /// - cacheURL: The intended URL that should be the storage folder.
  210. ///
  211. /// This issue typically arises due to an extreme lack of space on the disk storage. Kingfisher fails to create
  212. /// the cache folder under these circumstances, rendering the disk storage unusable. In such cases, it is
  213. /// recommended to prompt the user to free up storage space and restart the app to restore functionality.
  214. ///
  215. /// Error Code: 3011
  216. case diskStorageIsNotReady(cacheURL: URL)
  217. /// The resource is expected on the disk, but now missing for some reason.
  218. ///
  219. /// This happens when the expected resource is not on the disk for some reason during loading a live photo.
  220. ///
  221. /// Error Code: 3012
  222. case missingLivePhotoResourceOnDisk(_ resource: LivePhotoResource)
  223. }
  224. /// Represents the error reason during image processing phase.
  225. public enum ProcessorErrorReason: Sendable {
  226. /// Image processing has failed, and there is no valid output image generated by the processor.
  227. ///
  228. /// - Parameters:
  229. /// - processor: The `ImageProcessor` responsible for processing the image or its data in `item`.
  230. /// - item: The image or its data content.
  231. ///
  232. /// Error Code: 4001
  233. case processingFailed(processor: any ImageProcessor, item: ImageProcessItem)
  234. }
  235. /// Represents the error reason during image setting in a view related class.
  236. public enum ImageSettingErrorReason: Sendable {
  237. /// The input resource is empty or `nil`.
  238. ///
  239. /// Error Code: 5001
  240. case emptySource
  241. /// The resource task is completed, but it is not the one that was expected. This typically occurs when you set
  242. /// another resource on the view without canceling the current ongoing task. The previous task will fail with the
  243. /// `.notCurrentSourceTask` error when a result is obtained, regardless of whether it was successful or not for
  244. /// that task.
  245. ///
  246. /// - Parameters:
  247. /// - result: The `RetrieveImageResult` if the source task is completed without any issues. `nil` if an error occurred.
  248. /// - error: The `Error` if there was a problem during the image setting task. `nil` if the task completed successfully.
  249. /// - source: The original source value of the task.
  250. ///
  251. /// Error Code: 5002
  252. case notCurrentSourceTask(result: RetrieveImageResult?, error: (any Error)?, source: Source)
  253. /// An error occurs while retrieving data from an `ImageDataProvider`.
  254. ///
  255. /// - Parameters:
  256. /// - provider: The ``ImageDataProvider`` that encountered the error.
  257. /// - error: The underlying error that describes why this error occurred.
  258. ///
  259. /// Error Code: 5003
  260. case dataProviderError(provider: any ImageDataProvider, error: any Error)
  261. /// No more alternative ``Source`` can be used in current loading process. It means that the
  262. /// ``KingfisherOptionsInfoItem/alternativeSources(_:)`` are set and Kingfisher tried to recovery from the original error, but still
  263. /// fails for all the given alternative sources. The associated value holds all the errors encountered during
  264. /// the load process, including the original source loading error and all the alternative sources errors.
  265. /// Code 5004.
  266. /// No more alternative `Source` can be used in the current loading process.
  267. ///
  268. /// - Parameters:
  269. /// - error : A ``PropagationError`` contains more information about the source and error.
  270. ///
  271. /// This means that the ``KingfisherOptionsInfoItem/alternativeSources(_:)`` option is set, and Kingfisher attempted to recover from the original error,
  272. /// but still failed for all the provided alternative sources. The associated value holds all the errors encountered during
  273. /// the loading process, including the original source loading error and all the alternative sources errors.
  274. ///
  275. /// Error Code: 5004
  276. case alternativeSourcesExhausted([PropagationError])
  277. /// The resource task is completed, but it is not the one that was expected. This typically occurs when you set
  278. /// another resource on the view without canceling the current ongoing task. The previous task will fail with the
  279. /// `.notCurrentLivePhotoSourceTask` error when a result is obtained, regardless of whether it was successful or
  280. /// not for that task.
  281. ///
  282. /// This error is the live photo version of the `.notCurrentSourceTask` error (error 5002).
  283. ///
  284. /// - Parameters:
  285. /// - result: The `RetrieveImageResult` if the source task is completed without any issues. `nil` if an error occurred.
  286. /// - error: The `Error` if there was a problem during the image setting task. `nil` if the task completed successfully.
  287. /// - source: The original source value of the task.
  288. ///
  289. /// Error Code: 5005
  290. case notCurrentLivePhotoSourceTask(
  291. result: RetrieveLivePhotoResult?, error: (any Error)?, source: LivePhotoSource
  292. )
  293. /// The error happens during processing the live photo.
  294. ///
  295. /// When creating the final `PHLivePhoto` object from the downloaded image files, the internal Photos framework
  296. /// method `PHLivePhoto.request(withResourceFileURLs:placeholderImage:targetSize:contentMode:resultHandler:)`
  297. /// invokes its `resultHandler`. If the `info` dictionary in `resultHandler` contains `PHLivePhotoInfoErrorKey`,
  298. /// Kingfisher raises this error reason to pass the information to outside.
  299. ///
  300. /// If the processing fails due to any error that is not a `KingfisherError` case, Kingfisher also reports it
  301. /// with this reason.
  302. ///
  303. /// - Parameters:
  304. /// - result: The `RetrieveLivePhotoResult` if the source task is completed and a result is already existing.
  305. /// - error: The `NSError` if `PHLivePhotoInfoErrorKey` is contained in the `resultHandler` info dictionary.
  306. /// - source: The original source value of the task.
  307. ///
  308. /// - Note: It is possible that both `result` and `error` are non-nil value. Check the
  309. /// ``RetrieveLivePhotoResult/info`` property for the raw values that are from the Photos framework.
  310. ///
  311. /// Error Code: 5006
  312. case livePhotoResultError(result: RetrieveLivePhotoResult?, error: (any Error)?, source: LivePhotoSource)
  313. }
  314. // MARK: Member Cases
  315. /// Represents the error reasons that can occur during the networking request phase.
  316. case requestError(reason: RequestErrorReason)
  317. /// Represents the error reason that can occur during networking response phase.
  318. case responseError(reason: ResponseErrorReason)
  319. /// Represents the error reason that can occur during Kingfisher caching phase.
  320. case cacheError(reason: CacheErrorReason)
  321. /// Represents the error reason that can occur during image processing phase.
  322. case processorError(reason: ProcessorErrorReason)
  323. /// Represents the error reason that can occur during image setting in a view related class.
  324. case imageSettingError(reason: ImageSettingErrorReason)
  325. // MARK: Helper Properties & Methods
  326. /// A helper property to determine if this error is of type `RequestErrorReason.taskCancelled`.
  327. public var isTaskCancelled: Bool {
  328. if case .requestError(reason: .taskCancelled) = self {
  329. return true
  330. }
  331. return false
  332. }
  333. /// Helper method to check whether this error is a ``ResponseErrorReason/invalidHTTPStatusCode(response:)``
  334. /// and the associated value is a given status code.
  335. ///
  336. /// - Parameter code: The given status code.
  337. /// - Returns: If `self` is a `ResponseErrorReason.invalidHTTPStatusCode` error
  338. /// and its status code equals to `code`, `true` is returned. Otherwise, `false`.
  339. ///
  340. /// A helper method for checking HTTP status code.
  341. ///
  342. /// Use this helper method to determine whether this error corresponds to a
  343. /// ``ResponseErrorReason/invalidHTTPStatusCode(response:)`` with a specific status code.
  344. ///
  345. /// - Parameter code: The desired HTTP status code for comparison.
  346. /// - Returns: `true` if the error is of type ``ResponseErrorReason/invalidHTTPStatusCode(response:)`` and its
  347. /// status code matches the provided `code`, otherwise `false`.
  348. public func isInvalidResponseStatusCode(_ code: Int) -> Bool {
  349. if case .responseError(reason: .invalidHTTPStatusCode(let response)) = self {
  350. return response.statusCode == code
  351. }
  352. return false
  353. }
  354. /// A helper method for checking the error is type of ``ResponseErrorReason/invalidHTTPStatusCode(response:)``.
  355. public var isInvalidResponseStatusCode: Bool {
  356. if case .responseError(reason: .invalidHTTPStatusCode) = self {
  357. return true
  358. }
  359. return false
  360. }
  361. /// A helper property that indicates whether this error is of type
  362. /// ``ImageSettingErrorReason/notCurrentSourceTask(result:error:source:)`` or not.
  363. ///
  364. /// This property is used to check if a new image setting task starts while the old one is still running.
  365. /// In such a scenario, the identifier of the new task will overwrite the identifier of the old task.
  366. ///
  367. /// When the old task finishes, a ``ImageSettingErrorReason/notCurrentSourceTask(result:error:source:)`` error will
  368. /// be raised to notify you that the setting process has completed with a certain result, but the image view or
  369. /// button has not been updated.
  370. ///
  371. /// - Returns: `true` if the error is of type ``ImageSettingErrorReason/notCurrentSourceTask(result:error:source:)``,
  372. /// `false` otherwise.
  373. public var isNotCurrentTask: Bool {
  374. if case .imageSettingError(reason: .notCurrentSourceTask(_, _, _)) = self {
  375. return true
  376. }
  377. return false
  378. }
  379. var isLowDataModeConstrained: Bool {
  380. if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *),
  381. case .responseError(reason: .URLSessionError(let sessionError)) = self,
  382. let urlError = sessionError as? URLError,
  383. urlError.networkUnavailableReason == .constrained
  384. {
  385. return true
  386. }
  387. return false
  388. }
  389. }
  390. // MARK: - LocalizedError Conforming
  391. extension KingfisherError: LocalizedError {
  392. /// Provides a localized message describing the error that occurred.
  393. ///
  394. /// Use this property to obtain a human-readable description of the error for display to the user.
  395. public var errorDescription: String? {
  396. switch self {
  397. case .requestError(let reason): return reason.errorDescription
  398. case .responseError(let reason): return reason.errorDescription
  399. case .cacheError(let reason): return reason.errorDescription
  400. case .processorError(let reason): return reason.errorDescription
  401. case .imageSettingError(let reason): return reason.errorDescription
  402. }
  403. }
  404. }
  405. // MARK: - CustomNSError Conforming
  406. extension KingfisherError: CustomNSError {
  407. /// The error domain for ``KingfisherError``. All errors generated by Kingfisher are categorized under this domain.
  408. ///
  409. /// When handling errors from the Kingfisher library, you can use this domain to identify and distinguish them
  410. /// from other types of errors in your application.
  411. ///
  412. /// - Note: The error domain is a string identifier associated with each error.
  413. public static let domain = "com.onevcat.Kingfisher.Error"
  414. /// Represents the error code within the specified error domain.
  415. ///
  416. /// Use this property to retrieve the specific error code associated with a ``KingfisherError``. The error code
  417. /// provides additional context and information about the error, allowing you to handle and respond to different
  418. /// error scenarios.
  419. ///
  420. /// - Note: Error codes are numerical values associated with each error within a domain. Check the error code in the
  421. /// API reference of each error reason for the detail.
  422. ///
  423. /// - Returns: The error code as an integer.
  424. public var errorCode: Int {
  425. switch self {
  426. case .requestError(let reason): return reason.errorCode
  427. case .responseError(let reason): return reason.errorCode
  428. case .cacheError(let reason): return reason.errorCode
  429. case .processorError(let reason): return reason.errorCode
  430. case .imageSettingError(let reason): return reason.errorCode
  431. }
  432. }
  433. }
  434. extension KingfisherError.RequestErrorReason {
  435. var errorDescription: String? {
  436. switch self {
  437. case .emptyRequest:
  438. return "The request is empty or `nil`."
  439. case .invalidURL(let request):
  440. return "The request contains an invalid or empty URL. Request: \(request)."
  441. case .taskCancelled(let task, let token):
  442. return "The session task was cancelled. Task: \(task), cancel token: \(token)."
  443. case .livePhotoTaskCancelled(let source):
  444. return "The live photo download task was cancelled. Source: \(source)"
  445. }
  446. }
  447. var errorCode: Int {
  448. switch self {
  449. case .emptyRequest: return 1001
  450. case .invalidURL: return 1002
  451. case .taskCancelled: return 1003
  452. case .livePhotoTaskCancelled: return 1004
  453. }
  454. }
  455. }
  456. extension KingfisherError.ResponseErrorReason {
  457. var errorDescription: String? {
  458. switch self {
  459. case .invalidURLResponse(let response):
  460. return "The URL response is invalid: \(response)"
  461. case .invalidHTTPStatusCode(let response):
  462. return "The HTTP status code in response is invalid. Code: \(response.statusCode), response: \(response)."
  463. case .URLSessionError(let error):
  464. return "A URL session error happened. The underlying error: \(error)"
  465. case .dataModifyingFailed(let task):
  466. return "The data modifying delegate returned `nil` for the downloaded data. Task: \(task)."
  467. case .noURLResponse(let task):
  468. return "No URL response received. Task: \(task)."
  469. case .cancelledByDelegate(let response):
  470. return "The downloading task is cancelled by the downloader delegate. Response: \(response)."
  471. }
  472. }
  473. var errorCode: Int {
  474. switch self {
  475. case .invalidURLResponse: return 2001
  476. case .invalidHTTPStatusCode: return 2002
  477. case .URLSessionError: return 2003
  478. case .dataModifyingFailed: return 2004
  479. case .noURLResponse: return 2005
  480. case .cancelledByDelegate: return 2006
  481. }
  482. }
  483. }
  484. extension KingfisherError.CacheErrorReason {
  485. var errorDescription: String? {
  486. switch self {
  487. case .fileEnumeratorCreationFailed(let url):
  488. return "Cannot create file enumerator for URL: \(url)."
  489. case .invalidFileEnumeratorContent(let url):
  490. return "Cannot get contents from the file enumerator at URL: \(url)."
  491. case .invalidURLResource(let error, let key, let url):
  492. return "Cannot get URL resource values or data for the given URL: \(url). " +
  493. "Cache key: \(key). Underlying error: \(error)"
  494. case .cannotLoadDataFromDisk(let url, let error):
  495. return "Cannot load data from disk at URL: \(url). Underlying error: \(error)"
  496. case .cannotCreateDirectory(let path, let error):
  497. return "Cannot create directory at given path: Path: \(path). Underlying error: \(error)"
  498. case .imageNotExisting(let key):
  499. return "The image is not in cache, but you requires it should only be " +
  500. "from cache by enabling the `.onlyFromCache` option. Key: \(key)."
  501. case .cannotConvertToData(let object, let error):
  502. return "Cannot convert the input object to a `Data` object when storing it to disk cache. " +
  503. "Object: \(object). Underlying error: \(error)"
  504. case .cannotSerializeImage(let image, let originalData, let serializer):
  505. return "Cannot serialize an image due to the cache serializer returning `nil`. " +
  506. "Image: \(String(describing:image)), original data: \(String(describing: originalData)), " +
  507. "serializer: \(serializer)."
  508. case .cannotCreateCacheFile(let fileURL, let key, let data, let error):
  509. return "Cannot create cache file at url: \(fileURL), key: \(key), data length: \(data.count). " +
  510. "Underlying foundation error: \(error)."
  511. case .cannotSetCacheFileAttribute(let filePath, let attributes, let error):
  512. return "Cannot set file attribute for the cache file at path: \(filePath), attributes: \(attributes)." +
  513. "Underlying foundation error: \(error)."
  514. case .diskStorageIsNotReady(let cacheURL):
  515. return "The disk storage is not ready to use yet at URL: '\(cacheURL)'. " +
  516. "This is usually caused by extremely lack of disk space. Ask users to free up some space and restart the app."
  517. case .missingLivePhotoResourceOnDisk(let resource):
  518. return "The live photo resource '\(resource)' is missing in the cache. Usually a re-download" +
  519. " can fix this issue."
  520. }
  521. }
  522. var errorCode: Int {
  523. switch self {
  524. case .fileEnumeratorCreationFailed: return 3001
  525. case .invalidFileEnumeratorContent: return 3002
  526. case .invalidURLResource: return 3003
  527. case .cannotLoadDataFromDisk: return 3004
  528. case .cannotCreateDirectory: return 3005
  529. case .imageNotExisting: return 3006
  530. case .cannotConvertToData: return 3007
  531. case .cannotSerializeImage: return 3008
  532. case .cannotCreateCacheFile: return 3009
  533. case .cannotSetCacheFileAttribute: return 3010
  534. case .diskStorageIsNotReady: return 3011
  535. case .missingLivePhotoResourceOnDisk: return 3012
  536. }
  537. }
  538. }
  539. extension KingfisherError.ProcessorErrorReason {
  540. var errorDescription: String? {
  541. switch self {
  542. case .processingFailed(let processor, let item):
  543. return "Processing image failed. Processor: \(processor). Processing item: \(item)."
  544. }
  545. }
  546. var errorCode: Int {
  547. switch self {
  548. case .processingFailed: return 4001
  549. }
  550. }
  551. }
  552. extension KingfisherError.ImageSettingErrorReason {
  553. var errorDescription: String? {
  554. switch self {
  555. case .emptySource:
  556. return "The input resource is empty."
  557. case .notCurrentSourceTask(let result, let error, let resource):
  558. if let result = result {
  559. return "Retrieving resource succeeded, but this source is " +
  560. "not the one currently expected. Result: \(result). Resource: \(resource)."
  561. } else if let error = error {
  562. return "Retrieving resource failed, and this resource is " +
  563. "not the one currently expected. Error: \(error). Resource: \(resource)."
  564. } else {
  565. return nil
  566. }
  567. case .dataProviderError(let provider, let error):
  568. return "Image data provider fails to provide data. Provider: \(provider), error: \(error)"
  569. case .alternativeSourcesExhausted(let errors):
  570. return "Image setting from alternative sources failed: \(errors)"
  571. case .notCurrentLivePhotoSourceTask(let result, let error, let source):
  572. if let result = result {
  573. return "Retrieving live photo resource succeeded, but this source is " +
  574. "not the one currently expected. Result: \(result). Resource: \(source)."
  575. } else if let error = error {
  576. return "Retrieving live photo resource failed, and this resource is " +
  577. "not the one currently expected. Error: \(error). Resource: \(source)."
  578. } else {
  579. return nil
  580. }
  581. case .livePhotoResultError(let result, let error, let source):
  582. return "An error occurred while processing live photo. Source: \(source). " +
  583. "Result: \(String(describing: result)). Error: \(String(describing: error))"
  584. }
  585. }
  586. var errorCode: Int {
  587. switch self {
  588. case .emptySource: return 5001
  589. case .notCurrentSourceTask: return 5002
  590. case .dataProviderError: return 5003
  591. case .alternativeSourcesExhausted: return 5004
  592. case .notCurrentLivePhotoSourceTask: return 5005
  593. case .livePhotoResultError: return 5006
  594. }
  595. }
  596. }