KingfisherError.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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. }
  218. /// Represents the error reason during image processing phase.
  219. public enum ProcessorErrorReason: Sendable {
  220. /// Image processing has failed, and there is no valid output image generated by the processor.
  221. ///
  222. /// - Parameters:
  223. /// - processor: The `ImageProcessor` responsible for processing the image or its data in `item`.
  224. /// - item: The image or its data content.
  225. ///
  226. /// Error Code: 4001
  227. case processingFailed(processor: any ImageProcessor, item: ImageProcessItem)
  228. }
  229. /// Represents the error reason during image setting in a view related class.
  230. public enum ImageSettingErrorReason: Sendable {
  231. /// The input resource is empty or `nil`.
  232. ///
  233. /// Error Code: 5001
  234. case emptySource
  235. /// The resource task is completed, but it is not the one that was expected. This typically occurs when you set
  236. /// another resource on the view without canceling the current ongoing task. The previous task will fail with the
  237. /// `.notCurrentSourceTask` error when a result is obtained, regardless of whether it was successful or not for
  238. /// that task.
  239. ///
  240. /// - Parameters:
  241. /// - result: The `RetrieveImageResult` if the source task is completed without any issues. `nil` if an error occurred.
  242. /// - error: The `Error` if there was a problem during the image setting task. `nil` if the task completed successfully.
  243. /// - source: The original source value of the task.
  244. ///
  245. /// Error Code: 5002
  246. case notCurrentSourceTask(result: RetrieveImageResult?, error: (any Error)?, source: Source)
  247. /// An error occurs while retrieving data from an `ImageDataProvider`.
  248. ///
  249. /// - Parameters:
  250. /// - provider: The ``ImageDataProvider`` that encountered the error.
  251. /// - error: The underlying error that describes why this error occurred.
  252. ///
  253. /// Error Code: 5003
  254. case dataProviderError(provider: any ImageDataProvider, error: any Error)
  255. /// No more alternative ``Source`` can be used in current loading process. It means that the
  256. /// ``KingfisherOptionsInfoItem/alternativeSources(_:)`` are set and Kingfisher tried to recovery from the original error, but still
  257. /// fails for all the given alternative sources. The associated value holds all the errors encountered during
  258. /// the load process, including the original source loading error and all the alternative sources errors.
  259. /// Code 5004.
  260. /// No more alternative `Source` can be used in the current loading process.
  261. ///
  262. /// - Parameters:
  263. /// - error : A ``PropagationError`` contains more information about the source and error.
  264. ///
  265. /// This means that the ``KingfisherOptionsInfoItem/alternativeSources(_:)`` option is set, and Kingfisher attempted to recover from the original error,
  266. /// but still failed for all the provided alternative sources. The associated value holds all the errors encountered during
  267. /// the loading process, including the original source loading error and all the alternative sources errors.
  268. ///
  269. /// Error Code: 5004
  270. case alternativeSourcesExhausted([PropagationError])
  271. /// The resource task is completed, but it is not the one that was expected. This typically occurs when you set
  272. /// another resource on the view without canceling the current ongoing task. The previous task will fail with the
  273. /// `.notCurrentLivePhotoSourceTask` error when a result is obtained, regardless of whether it was successful or
  274. /// not for that task.
  275. ///
  276. /// This error is the live photo version of the `.notCurrentSourceTask` error (error 5002).
  277. ///
  278. /// - Parameters:
  279. /// - result: The `RetrieveImageResult` if the source task is completed without any issues. `nil` if an error occurred.
  280. /// - error: The `Error` if there was a problem during the image setting task. `nil` if the task completed successfully.
  281. /// - source: The original source value of the task.
  282. ///
  283. /// Error Code: 5005
  284. case notCurrentLivePhotoSourceTask(
  285. result: RetrieveLivePhotoResult?, error: (any Error)?, source: LivePhotoSource
  286. )
  287. /// The error happens during processing the live photo.
  288. ///
  289. /// When creating the final `PHLivePhoto` object from the downloaded image files, the internal Photos framework
  290. /// method `PHLivePhoto.request(withResourceFileURLs:placeholderImage:targetSize:contentMode:resultHandler:)`
  291. /// invokes its `resultHandler`. If the `info` dictionary in `resultHandler` contains `PHLivePhotoInfoErrorKey`,
  292. /// Kingfisher raises this error reason to pass the information to outside.
  293. ///
  294. /// If the processing fails due to any error that is not a `KingfisherError` case, Kingfisher also reports it
  295. /// with this reason.
  296. ///
  297. /// - Parameters:
  298. /// - result: The `RetrieveLivePhotoResult` if the source task is completed and a result is already existing.
  299. /// - error: The `NSError` if `PHLivePhotoInfoErrorKey` is contained in the `resultHandler` info dictionary.
  300. /// - source: The original source value of the task.
  301. ///
  302. /// - Note: It is possible that both `result` and `error` are non-nil value. Check the
  303. /// ``RetrieveLivePhotoResult/info`` property for the raw values that are from the Photos framework.
  304. ///
  305. /// Error Code: 5006
  306. case livePhotoResultError(result: RetrieveLivePhotoResult?, error: (any Error)?, source: LivePhotoSource)
  307. }
  308. // MARK: Member Cases
  309. /// Represents the error reasons that can occur during the networking request phase.
  310. case requestError(reason: RequestErrorReason)
  311. /// Represents the error reason that can occur during networking response phase.
  312. case responseError(reason: ResponseErrorReason)
  313. /// Represents the error reason that can occur during Kingfisher caching phase.
  314. case cacheError(reason: CacheErrorReason)
  315. /// Represents the error reason that can occur during image processing phase.
  316. case processorError(reason: ProcessorErrorReason)
  317. /// Represents the error reason that can occur during image setting in a view related class.
  318. case imageSettingError(reason: ImageSettingErrorReason)
  319. // MARK: Helper Properties & Methods
  320. /// A helper property to determine if this error is of type `RequestErrorReason.taskCancelled`.
  321. public var isTaskCancelled: Bool {
  322. if case .requestError(reason: .taskCancelled) = self {
  323. return true
  324. }
  325. return false
  326. }
  327. /// Helper method to check whether this error is a ``ResponseErrorReason/invalidHTTPStatusCode(response:)``
  328. /// and the associated value is a given status code.
  329. ///
  330. /// - Parameter code: The given status code.
  331. /// - Returns: If `self` is a `ResponseErrorReason.invalidHTTPStatusCode` error
  332. /// and its status code equals to `code`, `true` is returned. Otherwise, `false`.
  333. ///
  334. /// A helper method for checking HTTP status code.
  335. ///
  336. /// Use this helper method to determine whether this error corresponds to a
  337. /// ``ResponseErrorReason/invalidHTTPStatusCode(response:)`` with a specific status code.
  338. ///
  339. /// - Parameter code: The desired HTTP status code for comparison.
  340. /// - Returns: `true` if the error is of type ``ResponseErrorReason/invalidHTTPStatusCode(response:)`` and its
  341. /// status code matches the provided `code`, otherwise `false`.
  342. public func isInvalidResponseStatusCode(_ code: Int) -> Bool {
  343. if case .responseError(reason: .invalidHTTPStatusCode(let response)) = self {
  344. return response.statusCode == code
  345. }
  346. return false
  347. }
  348. /// A helper method for checking the error is type of ``ResponseErrorReason/invalidHTTPStatusCode(response:)``.
  349. public var isInvalidResponseStatusCode: Bool {
  350. if case .responseError(reason: .invalidHTTPStatusCode) = self {
  351. return true
  352. }
  353. return false
  354. }
  355. /// A helper property that indicates whether this error is of type
  356. /// ``ImageSettingErrorReason/notCurrentSourceTask(result:error:source:)`` or not.
  357. ///
  358. /// This property is used to check if a new image setting task starts while the old one is still running.
  359. /// In such a scenario, the identifier of the new task will overwrite the identifier of the old task.
  360. ///
  361. /// When the old task finishes, a ``ImageSettingErrorReason/notCurrentSourceTask(result:error:source:)`` error will
  362. /// be raised to notify you that the setting process has completed with a certain result, but the image view or
  363. /// button has not been updated.
  364. ///
  365. /// - Returns: `true` if the error is of type ``ImageSettingErrorReason/notCurrentSourceTask(result:error:source:)``,
  366. /// `false` otherwise.
  367. public var isNotCurrentTask: Bool {
  368. if case .imageSettingError(reason: .notCurrentSourceTask(_, _, _)) = self {
  369. return true
  370. }
  371. return false
  372. }
  373. var isLowDataModeConstrained: Bool {
  374. if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *),
  375. case .responseError(reason: .URLSessionError(let sessionError)) = self,
  376. let urlError = sessionError as? URLError,
  377. urlError.networkUnavailableReason == .constrained
  378. {
  379. return true
  380. }
  381. return false
  382. }
  383. }
  384. // MARK: - LocalizedError Conforming
  385. extension KingfisherError: LocalizedError {
  386. /// Provides a localized message describing the error that occurred.
  387. ///
  388. /// Use this property to obtain a human-readable description of the error for display to the user.
  389. public var errorDescription: String? {
  390. switch self {
  391. case .requestError(let reason): return reason.errorDescription
  392. case .responseError(let reason): return reason.errorDescription
  393. case .cacheError(let reason): return reason.errorDescription
  394. case .processorError(let reason): return reason.errorDescription
  395. case .imageSettingError(let reason): return reason.errorDescription
  396. }
  397. }
  398. }
  399. // MARK: - CustomNSError Conforming
  400. extension KingfisherError: CustomNSError {
  401. /// The error domain for ``KingfisherError``. All errors generated by Kingfisher are categorized under this domain.
  402. ///
  403. /// When handling errors from the Kingfisher library, you can use this domain to identify and distinguish them
  404. /// from other types of errors in your application.
  405. ///
  406. /// - Note: The error domain is a string identifier associated with each error.
  407. public static let domain = "com.onevcat.Kingfisher.Error"
  408. /// Represents the error code within the specified error domain.
  409. ///
  410. /// Use this property to retrieve the specific error code associated with a ``KingfisherError``. The error code
  411. /// provides additional context and information about the error, allowing you to handle and respond to different
  412. /// error scenarios.
  413. ///
  414. /// - Note: Error codes are numerical values associated with each error within a domain. Check the error code in the
  415. /// API reference of each error reason for the detail.
  416. ///
  417. /// - Returns: The error code as an integer.
  418. public var errorCode: Int {
  419. switch self {
  420. case .requestError(let reason): return reason.errorCode
  421. case .responseError(let reason): return reason.errorCode
  422. case .cacheError(let reason): return reason.errorCode
  423. case .processorError(let reason): return reason.errorCode
  424. case .imageSettingError(let reason): return reason.errorCode
  425. }
  426. }
  427. }
  428. extension KingfisherError.RequestErrorReason {
  429. var errorDescription: String? {
  430. switch self {
  431. case .emptyRequest:
  432. return "The request is empty or `nil`."
  433. case .invalidURL(let request):
  434. return "The request contains an invalid or empty URL. Request: \(request)."
  435. case .taskCancelled(let task, let token):
  436. return "The session task was cancelled. Task: \(task), cancel token: \(token)."
  437. case .livePhotoTaskCancelled(let source):
  438. return "The live photo download task was cancelled. Source: \(source)"
  439. }
  440. }
  441. var errorCode: Int {
  442. switch self {
  443. case .emptyRequest: return 1001
  444. case .invalidURL: return 1002
  445. case .taskCancelled: return 1003
  446. case .livePhotoTaskCancelled: return 1004
  447. }
  448. }
  449. }
  450. extension KingfisherError.ResponseErrorReason {
  451. var errorDescription: String? {
  452. switch self {
  453. case .invalidURLResponse(let response):
  454. return "The URL response is invalid: \(response)"
  455. case .invalidHTTPStatusCode(let response):
  456. return "The HTTP status code in response is invalid. Code: \(response.statusCode), response: \(response)."
  457. case .URLSessionError(let error):
  458. return "A URL session error happened. The underlying error: \(error)"
  459. case .dataModifyingFailed(let task):
  460. return "The data modifying delegate returned `nil` for the downloaded data. Task: \(task)."
  461. case .noURLResponse(let task):
  462. return "No URL response received. Task: \(task)."
  463. case .cancelledByDelegate(let response):
  464. return "The downloading task is cancelled by the downloader delegate. Response: \(response)."
  465. }
  466. }
  467. var errorCode: Int {
  468. switch self {
  469. case .invalidURLResponse: return 2001
  470. case .invalidHTTPStatusCode: return 2002
  471. case .URLSessionError: return 2003
  472. case .dataModifyingFailed: return 2004
  473. case .noURLResponse: return 2005
  474. case .cancelledByDelegate: return 2006
  475. }
  476. }
  477. }
  478. extension KingfisherError.CacheErrorReason {
  479. var errorDescription: String? {
  480. switch self {
  481. case .fileEnumeratorCreationFailed(let url):
  482. return "Cannot create file enumerator for URL: \(url)."
  483. case .invalidFileEnumeratorContent(let url):
  484. return "Cannot get contents from the file enumerator at URL: \(url)."
  485. case .invalidURLResource(let error, let key, let url):
  486. return "Cannot get URL resource values or data for the given URL: \(url). " +
  487. "Cache key: \(key). Underlying error: \(error)"
  488. case .cannotLoadDataFromDisk(let url, let error):
  489. return "Cannot load data from disk at URL: \(url). Underlying error: \(error)"
  490. case .cannotCreateDirectory(let path, let error):
  491. return "Cannot create directory at given path: Path: \(path). Underlying error: \(error)"
  492. case .imageNotExisting(let key):
  493. return "The image is not in cache, but you requires it should only be " +
  494. "from cache by enabling the `.onlyFromCache` option. Key: \(key)."
  495. case .cannotConvertToData(let object, let error):
  496. return "Cannot convert the input object to a `Data` object when storing it to disk cache. " +
  497. "Object: \(object). Underlying error: \(error)"
  498. case .cannotSerializeImage(let image, let originalData, let serializer):
  499. return "Cannot serialize an image due to the cache serializer returning `nil`. " +
  500. "Image: \(String(describing:image)), original data: \(String(describing: originalData)), " +
  501. "serializer: \(serializer)."
  502. case .cannotCreateCacheFile(let fileURL, let key, let data, let error):
  503. return "Cannot create cache file at url: \(fileURL), key: \(key), data length: \(data.count). " +
  504. "Underlying foundation error: \(error)."
  505. case .cannotSetCacheFileAttribute(let filePath, let attributes, let error):
  506. return "Cannot set file attribute for the cache file at path: \(filePath), attributes: \(attributes)." +
  507. "Underlying foundation error: \(error)."
  508. case .diskStorageIsNotReady(let cacheURL):
  509. return "The disk storage is not ready to use yet at URL: '\(cacheURL)'. " +
  510. "This is usually caused by extremely lack of disk space. Ask users to free up some space and restart the app."
  511. }
  512. }
  513. var errorCode: Int {
  514. switch self {
  515. case .fileEnumeratorCreationFailed: return 3001
  516. case .invalidFileEnumeratorContent: return 3002
  517. case .invalidURLResource: return 3003
  518. case .cannotLoadDataFromDisk: return 3004
  519. case .cannotCreateDirectory: return 3005
  520. case .imageNotExisting: return 3006
  521. case .cannotConvertToData: return 3007
  522. case .cannotSerializeImage: return 3008
  523. case .cannotCreateCacheFile: return 3009
  524. case .cannotSetCacheFileAttribute: return 3010
  525. case .diskStorageIsNotReady: return 3011
  526. }
  527. }
  528. }
  529. extension KingfisherError.ProcessorErrorReason {
  530. var errorDescription: String? {
  531. switch self {
  532. case .processingFailed(let processor, let item):
  533. return "Processing image failed. Processor: \(processor). Processing item: \(item)."
  534. }
  535. }
  536. var errorCode: Int {
  537. switch self {
  538. case .processingFailed: return 4001
  539. }
  540. }
  541. }
  542. extension KingfisherError.ImageSettingErrorReason {
  543. var errorDescription: String? {
  544. switch self {
  545. case .emptySource:
  546. return "The input resource is empty."
  547. case .notCurrentSourceTask(let result, let error, let resource):
  548. if let result = result {
  549. return "Retrieving resource succeeded, but this source is " +
  550. "not the one currently expected. Result: \(result). Resource: \(resource)."
  551. } else if let error = error {
  552. return "Retrieving resource failed, and this resource is " +
  553. "not the one currently expected. Error: \(error). Resource: \(resource)."
  554. } else {
  555. return nil
  556. }
  557. case .dataProviderError(let provider, let error):
  558. return "Image data provider fails to provide data. Provider: \(provider), error: \(error)"
  559. case .alternativeSourcesExhausted(let errors):
  560. return "Image setting from alternative sources failed: \(errors)"
  561. case .notCurrentLivePhotoSourceTask(let result, let error, let source):
  562. if let result = result {
  563. return "Retrieving live photo resource succeeded, but this source is " +
  564. "not the one currently expected. Result: \(result). Resource: \(source)."
  565. } else if let error = error {
  566. return "Retrieving live photo resource failed, and this resource is " +
  567. "not the one currently expected. Error: \(error). Resource: \(source)."
  568. } else {
  569. return nil
  570. }
  571. case .livePhotoResultError(let result, let error, let source):
  572. return "An error occurred while processing live photo. Source: \(source). " +
  573. "Result: \(String(describing: result)). Error: \(String(describing: error))"
  574. }
  575. }
  576. var errorCode: Int {
  577. switch self {
  578. case .emptySource: return 5001
  579. case .notCurrentSourceTask: return 5002
  580. case .dataProviderError: return 5003
  581. case .alternativeSourcesExhausted: return 5004
  582. case .notCurrentLivePhotoSourceTask: return 5005
  583. case .livePhotoResultError: return 5006
  584. }
  585. }
  586. }