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.

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