AFError.swift 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. //
  2. // AFError.swift
  3. //
  4. // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. /// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with
  26. /// their own associated reasons.
  27. public enum AFError: Error {
  28. /// The underlying reason the `.multipartEncodingFailed` error occurred.
  29. public enum MultipartEncodingFailureReason {
  30. /// The `fileURL` provided for reading an encodable body part isn't a file `URL`.
  31. case bodyPartURLInvalid(url: URL)
  32. /// The filename of the `fileURL` provided has either an empty `lastPathComponent` or `pathExtension.
  33. case bodyPartFilenameInvalid(in: URL)
  34. /// The file at the `fileURL` provided was not reachable.
  35. case bodyPartFileNotReachable(at: URL)
  36. /// Attempting to check the reachability of the `fileURL` provided threw an error.
  37. case bodyPartFileNotReachableWithError(atURL: URL, error: Error)
  38. /// The file at the `fileURL` provided is actually a directory.
  39. case bodyPartFileIsDirectory(at: URL)
  40. /// The size of the file at the `fileURL` provided was not returned by the system.
  41. case bodyPartFileSizeNotAvailable(at: URL)
  42. /// The attempt to find the size of the file at the `fileURL` provided threw an error.
  43. case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error)
  44. /// An `InputStream` could not be created for the provided `fileURL`.
  45. case bodyPartInputStreamCreationFailed(for: URL)
  46. /// An `OutputStream` could not be created when attempting to write the encoded data to disk.
  47. case outputStreamCreationFailed(for: URL)
  48. /// The encoded body data could not be written to disk because a file already exists at the provided `fileURL`.
  49. case outputStreamFileAlreadyExists(at: URL)
  50. /// The `fileURL` provided for writing the encoded body data to disk is not a file `URL`.
  51. case outputStreamURLInvalid(url: URL)
  52. /// The attempt to write the encoded body data to disk failed with an underlying error.
  53. case outputStreamWriteFailed(error: Error)
  54. /// The attempt to read an encoded body part `InputStream` failed with underlying system error.
  55. case inputStreamReadFailed(error: Error)
  56. }
  57. /// Represents unexpected input stream length that occur when encoding the `MultipartFormData`. Instances will be
  58. /// embedded within an `AFError.multipartEncodingFailed` `.inputStreamReadFailed` case.
  59. public struct UnexpectedInputStreamLength: Error {
  60. /// The expected byte count to read.
  61. public var bytesExpected: UInt64
  62. /// The actual byte count read.
  63. public var bytesRead: UInt64
  64. }
  65. /// The underlying reason the `.parameterEncodingFailed` error occurred.
  66. public enum ParameterEncodingFailureReason {
  67. /// The `URLRequest` did not have a `URL` to encode.
  68. case missingURL
  69. /// JSON serialization failed with an underlying system error during the encoding process.
  70. case jsonEncodingFailed(error: Error)
  71. /// Custom parameter encoding failed due to the associated `Error`.
  72. case customEncodingFailed(error: Error)
  73. }
  74. /// The underlying reason the `.parameterEncoderFailed` error occurred.
  75. public enum ParameterEncoderFailureReason {
  76. /// Possible missing components.
  77. public enum RequiredComponent {
  78. /// The `URL` was missing or unable to be extracted from the passed `URLRequest` or during encoding.
  79. case url
  80. /// The `HTTPMethod` could not be extracted from the passed `URLRequest`.
  81. case httpMethod(rawValue: String)
  82. }
  83. /// A `RequiredComponent` was missing during encoding.
  84. case missingRequiredComponent(RequiredComponent)
  85. /// The underlying encoder failed with the associated error.
  86. case encoderFailed(error: Error)
  87. }
  88. /// The underlying reason the `.responseValidationFailed` error occurred.
  89. public enum ResponseValidationFailureReason {
  90. /// The data file containing the server response did not exist.
  91. case dataFileNil
  92. /// The data file containing the server response at the associated `URL` could not be read.
  93. case dataFileReadFailed(at: URL)
  94. /// The response did not contain a `Content-Type` and the `acceptableContentTypes` provided did not contain a
  95. /// wildcard type.
  96. case missingContentType(acceptableContentTypes: [String])
  97. /// The response `Content-Type` did not match any type in the provided `acceptableContentTypes`.
  98. case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String)
  99. /// The response status code was not acceptable.
  100. case unacceptableStatusCode(code: Int)
  101. /// Custom response validation failed due to the associated `Error`.
  102. case customValidationFailed(error: Error)
  103. }
  104. /// The underlying reason the response serialization error occurred.
  105. public enum ResponseSerializationFailureReason {
  106. /// The server response contained no data or the data was zero length.
  107. case inputDataNilOrZeroLength
  108. /// The file containing the server response did not exist.
  109. case inputFileNil
  110. /// The file containing the server response could not be read from the associated `URL`.
  111. case inputFileReadFailed(at: URL)
  112. /// String serialization failed using the provided `String.Encoding`.
  113. case stringSerializationFailed(encoding: String.Encoding)
  114. /// JSON serialization failed with an underlying system error.
  115. case jsonSerializationFailed(error: Error)
  116. /// A `DataDecoder` failed to decode the response due to the associated `Error`.
  117. case decodingFailed(error: Error)
  118. /// A custom response serializer failed due to the associated `Error`.
  119. case customSerializationFailed(error: Error)
  120. /// Generic serialization failed for an empty response that wasn't type `Empty` but instead the associated type.
  121. case invalidEmptyResponse(type: String)
  122. }
  123. /// Underlying reason a server trust evaluation error occurred.
  124. public enum ServerTrustFailureReason {
  125. /// The output of a server trust evaluation.
  126. public struct Output {
  127. /// The host for which the evaluation was performed.
  128. public let host: String
  129. /// The `SecTrust` value which was evaluated.
  130. public let trust: SecTrust
  131. /// The `OSStatus` of evaluation operation.
  132. public let status: OSStatus
  133. /// The result of the evaluation operation.
  134. public let result: SecTrustResultType
  135. /// Creates an `Output` value from the provided values.
  136. init(_ host: String, _ trust: SecTrust, _ status: OSStatus, _ result: SecTrustResultType) {
  137. self.host = host
  138. self.trust = trust
  139. self.status = status
  140. self.result = result
  141. }
  142. }
  143. /// No `ServerTrustEvaluator` was found for the associated host.
  144. case noRequiredEvaluator(host: String)
  145. /// No certificates were found with which to perform the trust evaluation.
  146. case noCertificatesFound
  147. /// No public keys were found with which to perform the trust evaluation.
  148. case noPublicKeysFound
  149. /// During evaluation, application of the associated `SecPolicy` failed.
  150. case policyApplicationFailed(trust: SecTrust, policy: SecPolicy, status: OSStatus)
  151. /// During evaluation, setting the associated anchor certificates failed.
  152. case settingAnchorCertificatesFailed(status: OSStatus, certificates: [SecCertificate])
  153. /// During evaluation, creation of the revocation policy failed.
  154. case revocationPolicyCreationFailed
  155. /// `SecTrust` evaluation failed with the associated `Error`, if one was produced.
  156. case trustEvaluationFailed(error: Error?)
  157. /// Default evaluation failed with the associated `Output`.
  158. case defaultEvaluationFailed(output: Output)
  159. /// Host validation failed with the associated `Output`.
  160. case hostValidationFailed(output: Output)
  161. /// Revocation check failed with the associated `Output` and options.
  162. case revocationCheckFailed(output: Output, options: RevocationTrustEvaluator.Options)
  163. /// Certificate pinning failed.
  164. case certificatePinningFailed(host: String, trust: SecTrust, pinnedCertificates: [SecCertificate], serverCertificates: [SecCertificate])
  165. /// Public key pinning failed.
  166. case publicKeyPinningFailed(host: String, trust: SecTrust, pinnedKeys: [SecKey], serverKeys: [SecKey])
  167. /// Custom server trust evaluation failed due to the associated `Error`.
  168. case customEvaluationFailed(error: Error)
  169. }
  170. /// The underlying reason the `.urlRequestValidationFailed`
  171. public enum URLRequestValidationFailureReason {
  172. /// URLRequest with GET method had body data.
  173. case bodyDataInGETRequest(Data)
  174. }
  175. /// `UploadableConvertible` threw an error in `createUploadable()`.
  176. case createUploadableFailed(error: Error)
  177. /// `URLRequestConvertible` threw an error in `asURLRequest()`.
  178. case createURLRequestFailed(error: Error)
  179. /// `SessionDelegate` threw an error while attempting to move downloaded file to destination URL.
  180. case downloadedFileMoveFailed(error: Error, source: URL, destination: URL)
  181. /// `Request` was explicitly cancelled.
  182. case explicitlyCancelled
  183. /// `URLConvertible` type failed to create a valid `URL`.
  184. case invalidURL(url: URLConvertible)
  185. /// Multipart form encoding failed.
  186. case multipartEncodingFailed(reason: MultipartEncodingFailureReason)
  187. /// `ParameterEncoding` threw an error during the encoding process.
  188. case parameterEncodingFailed(reason: ParameterEncodingFailureReason)
  189. /// `ParameterEncoder` threw an error while running the encoder.
  190. case parameterEncoderFailed(reason: ParameterEncoderFailureReason)
  191. /// `RequestAdapter` threw an error during adaptation.
  192. case requestAdaptationFailed(error: Error)
  193. /// `RequestRetrier` threw an error during the request retry process.
  194. case requestRetryFailed(retryError: Error, originalError: Error)
  195. /// Response validation failed.
  196. case responseValidationFailed(reason: ResponseValidationFailureReason)
  197. /// Response serialization failed.
  198. case responseSerializationFailed(reason: ResponseSerializationFailureReason)
  199. /// `ServerTrustEvaluating` instance threw an error during trust evaluation.
  200. case serverTrustEvaluationFailed(reason: ServerTrustFailureReason)
  201. /// `Session` which issued the `Request` was deinitialized, most likely because its reference went out of scope.
  202. case sessionDeinitialized
  203. /// `Session` was explicitly invalidated, possibly with the `Error` produced by the underlying `URLSession`.
  204. case sessionInvalidated(error: Error?)
  205. /// `URLSessionTask` completed with error.
  206. case sessionTaskFailed(error: Error)
  207. /// `URLRequest` failed validation.
  208. case urlRequestValidationFailed(reason: URLRequestValidationFailureReason)
  209. }
  210. extension Error {
  211. /// Returns the instance cast as an `AFError`.
  212. public var asAFError: AFError? {
  213. self as? AFError
  214. }
  215. /// Returns the instance cast as an `AFError`. If casting fails, a `fatalError` with the specified `message` is thrown.
  216. public func asAFError(orFailWith message: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> AFError {
  217. guard let afError = self as? AFError else {
  218. fatalError(message(), file: file, line: line)
  219. }
  220. return afError
  221. }
  222. /// Casts the instance as `AFError` or returns `defaultAFError`
  223. func asAFError(or defaultAFError: @autoclosure () -> AFError) -> AFError {
  224. self as? AFError ?? defaultAFError()
  225. }
  226. }
  227. // MARK: - Error Booleans
  228. extension AFError {
  229. /// Returns whether the instance is `.sessionDeinitialized`.
  230. public var isSessionDeinitializedError: Bool {
  231. if case .sessionDeinitialized = self { return true }
  232. return false
  233. }
  234. /// Returns whether the instance is `.sessionInvalidated`.
  235. public var isSessionInvalidatedError: Bool {
  236. if case .sessionInvalidated = self { return true }
  237. return false
  238. }
  239. /// Returns whether the instance is `.explicitlyCancelled`.
  240. public var isExplicitlyCancelledError: Bool {
  241. if case .explicitlyCancelled = self { return true }
  242. return false
  243. }
  244. /// Returns whether the instance is `.invalidURL`.
  245. public var isInvalidURLError: Bool {
  246. if case .invalidURL = self { return true }
  247. return false
  248. }
  249. /// Returns whether the instance is `.parameterEncodingFailed`. When `true`, the `underlyingError` property will
  250. /// contain the associated value.
  251. public var isParameterEncodingError: Bool {
  252. if case .parameterEncodingFailed = self { return true }
  253. return false
  254. }
  255. /// Returns whether the instance is `.parameterEncoderFailed`. When `true`, the `underlyingError` property will
  256. /// contain the associated value.
  257. public var isParameterEncoderError: Bool {
  258. if case .parameterEncoderFailed = self { return true }
  259. return false
  260. }
  261. /// Returns whether the instance is `.multipartEncodingFailed`. When `true`, the `url` and `underlyingError`
  262. /// properties will contain the associated values.
  263. public var isMultipartEncodingError: Bool {
  264. if case .multipartEncodingFailed = self { return true }
  265. return false
  266. }
  267. /// Returns whether the instance is `.requestAdaptationFailed`. When `true`, the `underlyingError` property will
  268. /// contain the associated value.
  269. public var isRequestAdaptationError: Bool {
  270. if case .requestAdaptationFailed = self { return true }
  271. return false
  272. }
  273. /// Returns whether the instance is `.responseValidationFailed`. When `true`, the `acceptableContentTypes`,
  274. /// `responseContentType`, `responseCode`, and `underlyingError` properties will contain the associated values.
  275. public var isResponseValidationError: Bool {
  276. if case .responseValidationFailed = self { return true }
  277. return false
  278. }
  279. /// Returns whether the instance is `.responseSerializationFailed`. When `true`, the `failedStringEncoding` and
  280. /// `underlyingError` properties will contain the associated values.
  281. public var isResponseSerializationError: Bool {
  282. if case .responseSerializationFailed = self { return true }
  283. return false
  284. }
  285. /// Returns whether the instance is `.serverTrustEvaluationFailed`. When `true`, the `underlyingError` property will
  286. /// contain the associated value.
  287. public var isServerTrustEvaluationError: Bool {
  288. if case .serverTrustEvaluationFailed = self { return true }
  289. return false
  290. }
  291. /// Returns whether the instance is `requestRetryFailed`. When `true`, the `underlyingError` property will
  292. /// contain the associated value.
  293. public var isRequestRetryError: Bool {
  294. if case .requestRetryFailed = self { return true }
  295. return false
  296. }
  297. /// Returns whether the instance is `createUploadableFailed`. When `true`, the `underlyingError` property will
  298. /// contain the associated value.
  299. public var isCreateUploadableError: Bool {
  300. if case .createUploadableFailed = self { return true }
  301. return false
  302. }
  303. /// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will
  304. /// contain the associated value.
  305. public var isCreateURLRequestError: Bool {
  306. if case .createURLRequestFailed = self { return true }
  307. return false
  308. }
  309. /// Returns whether the instance is `downloadedFileMoveFailed`. When `true`, the `destination` and `underlyingError` properties will
  310. /// contain the associated values.
  311. public var isDownloadedFileMoveError: Bool {
  312. if case .downloadedFileMoveFailed = self { return true }
  313. return false
  314. }
  315. /// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will
  316. /// contain the associated value.
  317. public var isSessionTaskError: Bool {
  318. if case .sessionTaskFailed = self { return true }
  319. return false
  320. }
  321. }
  322. // MARK: - Convenience Properties
  323. extension AFError {
  324. /// The `URLConvertible` associated with the error.
  325. public var urlConvertible: URLConvertible? {
  326. guard case let .invalidURL(url) = self else { return nil }
  327. return url
  328. }
  329. /// The `URL` associated with the error.
  330. public var url: URL? {
  331. guard case let .multipartEncodingFailed(reason) = self else { return nil }
  332. return reason.url
  333. }
  334. /// The underlying `Error` responsible for generating the failure associated with `.sessionInvalidated`,
  335. /// `.parameterEncodingFailed`, `.parameterEncoderFailed`, `.multipartEncodingFailed`, `.requestAdaptationFailed`,
  336. /// `.responseSerializationFailed`, `.requestRetryFailed` errors.
  337. public var underlyingError: Error? {
  338. switch self {
  339. case let .multipartEncodingFailed(reason):
  340. return reason.underlyingError
  341. case let .parameterEncodingFailed(reason):
  342. return reason.underlyingError
  343. case let .parameterEncoderFailed(reason):
  344. return reason.underlyingError
  345. case let .requestAdaptationFailed(error):
  346. return error
  347. case let .requestRetryFailed(retryError, _):
  348. return retryError
  349. case let .responseValidationFailed(reason):
  350. return reason.underlyingError
  351. case let .responseSerializationFailed(reason):
  352. return reason.underlyingError
  353. case let .serverTrustEvaluationFailed(reason):
  354. return reason.underlyingError
  355. case let .sessionInvalidated(error):
  356. return error
  357. case let .createUploadableFailed(error):
  358. return error
  359. case let .createURLRequestFailed(error):
  360. return error
  361. case let .downloadedFileMoveFailed(error, _, _):
  362. return error
  363. case let .sessionTaskFailed(error):
  364. return error
  365. case .explicitlyCancelled,
  366. .invalidURL,
  367. .sessionDeinitialized,
  368. .urlRequestValidationFailed:
  369. return nil
  370. }
  371. }
  372. /// The acceptable `Content-Type`s of a `.responseValidationFailed` error.
  373. public var acceptableContentTypes: [String]? {
  374. guard case let .responseValidationFailed(reason) = self else { return nil }
  375. return reason.acceptableContentTypes
  376. }
  377. /// The response `Content-Type` of a `.responseValidationFailed` error.
  378. public var responseContentType: String? {
  379. guard case let .responseValidationFailed(reason) = self else { return nil }
  380. return reason.responseContentType
  381. }
  382. /// The response code of a `.responseValidationFailed` error.
  383. public var responseCode: Int? {
  384. guard case let .responseValidationFailed(reason) = self else { return nil }
  385. return reason.responseCode
  386. }
  387. /// The `String.Encoding` associated with a failed `.stringResponse()` call.
  388. public var failedStringEncoding: String.Encoding? {
  389. guard case let .responseSerializationFailed(reason) = self else { return nil }
  390. return reason.failedStringEncoding
  391. }
  392. /// The `source` URL of a `.downloadedFileMoveFailed` error.
  393. public var sourceURL: URL? {
  394. guard case let .downloadedFileMoveFailed(_, source, _) = self else { return nil }
  395. return source
  396. }
  397. /// The `destination` URL of a `.downloadedFileMoveFailed` error.
  398. public var destinationURL: URL? {
  399. guard case let .downloadedFileMoveFailed(_, _, destination) = self else { return nil }
  400. return destination
  401. }
  402. /// The download resume data of any underlying network error. Only produced by `DownloadRequest`s.
  403. public var downloadResumeData: Data? {
  404. (underlyingError as? URLError)?.userInfo[NSURLSessionDownloadTaskResumeData] as? Data
  405. }
  406. }
  407. extension AFError.ParameterEncodingFailureReason {
  408. var underlyingError: Error? {
  409. switch self {
  410. case let .jsonEncodingFailed(error),
  411. let .customEncodingFailed(error):
  412. return error
  413. case .missingURL:
  414. return nil
  415. }
  416. }
  417. }
  418. extension AFError.ParameterEncoderFailureReason {
  419. var underlyingError: Error? {
  420. switch self {
  421. case let .encoderFailed(error):
  422. return error
  423. case .missingRequiredComponent:
  424. return nil
  425. }
  426. }
  427. }
  428. extension AFError.MultipartEncodingFailureReason {
  429. var url: URL? {
  430. switch self {
  431. case let .bodyPartURLInvalid(url),
  432. let .bodyPartFilenameInvalid(url),
  433. let .bodyPartFileNotReachable(url),
  434. let .bodyPartFileIsDirectory(url),
  435. let .bodyPartFileSizeNotAvailable(url),
  436. let .bodyPartInputStreamCreationFailed(url),
  437. let .outputStreamCreationFailed(url),
  438. let .outputStreamFileAlreadyExists(url),
  439. let .outputStreamURLInvalid(url),
  440. let .bodyPartFileNotReachableWithError(url, _),
  441. let .bodyPartFileSizeQueryFailedWithError(url, _):
  442. return url
  443. case .outputStreamWriteFailed,
  444. .inputStreamReadFailed:
  445. return nil
  446. }
  447. }
  448. var underlyingError: Error? {
  449. switch self {
  450. case let .bodyPartFileNotReachableWithError(_, error),
  451. let .bodyPartFileSizeQueryFailedWithError(_, error),
  452. let .outputStreamWriteFailed(error),
  453. let .inputStreamReadFailed(error):
  454. return error
  455. case .bodyPartURLInvalid,
  456. .bodyPartFilenameInvalid,
  457. .bodyPartFileNotReachable,
  458. .bodyPartFileIsDirectory,
  459. .bodyPartFileSizeNotAvailable,
  460. .bodyPartInputStreamCreationFailed,
  461. .outputStreamCreationFailed,
  462. .outputStreamFileAlreadyExists,
  463. .outputStreamURLInvalid:
  464. return nil
  465. }
  466. }
  467. }
  468. extension AFError.ResponseValidationFailureReason {
  469. var acceptableContentTypes: [String]? {
  470. switch self {
  471. case let .missingContentType(types),
  472. let .unacceptableContentType(types, _):
  473. return types
  474. case .dataFileNil,
  475. .dataFileReadFailed,
  476. .unacceptableStatusCode,
  477. .customValidationFailed:
  478. return nil
  479. }
  480. }
  481. var responseContentType: String? {
  482. switch self {
  483. case let .unacceptableContentType(_, responseType):
  484. return responseType
  485. case .dataFileNil,
  486. .dataFileReadFailed,
  487. .missingContentType,
  488. .unacceptableStatusCode,
  489. .customValidationFailed:
  490. return nil
  491. }
  492. }
  493. var responseCode: Int? {
  494. switch self {
  495. case let .unacceptableStatusCode(code):
  496. return code
  497. case .dataFileNil,
  498. .dataFileReadFailed,
  499. .missingContentType,
  500. .unacceptableContentType,
  501. .customValidationFailed:
  502. return nil
  503. }
  504. }
  505. var underlyingError: Error? {
  506. switch self {
  507. case let .customValidationFailed(error):
  508. return error
  509. case .dataFileNil,
  510. .dataFileReadFailed,
  511. .missingContentType,
  512. .unacceptableContentType,
  513. .unacceptableStatusCode:
  514. return nil
  515. }
  516. }
  517. }
  518. extension AFError.ResponseSerializationFailureReason {
  519. var failedStringEncoding: String.Encoding? {
  520. switch self {
  521. case let .stringSerializationFailed(encoding):
  522. return encoding
  523. case .inputDataNilOrZeroLength,
  524. .inputFileNil,
  525. .inputFileReadFailed(_),
  526. .jsonSerializationFailed(_),
  527. .decodingFailed(_),
  528. .customSerializationFailed(_),
  529. .invalidEmptyResponse:
  530. return nil
  531. }
  532. }
  533. var underlyingError: Error? {
  534. switch self {
  535. case let .jsonSerializationFailed(error),
  536. let .decodingFailed(error),
  537. let .customSerializationFailed(error):
  538. return error
  539. case .inputDataNilOrZeroLength,
  540. .inputFileNil,
  541. .inputFileReadFailed,
  542. .stringSerializationFailed,
  543. .invalidEmptyResponse:
  544. return nil
  545. }
  546. }
  547. }
  548. extension AFError.ServerTrustFailureReason {
  549. var output: AFError.ServerTrustFailureReason.Output? {
  550. switch self {
  551. case let .defaultEvaluationFailed(output),
  552. let .hostValidationFailed(output),
  553. let .revocationCheckFailed(output, _):
  554. return output
  555. case .noRequiredEvaluator,
  556. .noCertificatesFound,
  557. .noPublicKeysFound,
  558. .policyApplicationFailed,
  559. .settingAnchorCertificatesFailed,
  560. .revocationPolicyCreationFailed,
  561. .trustEvaluationFailed,
  562. .certificatePinningFailed,
  563. .publicKeyPinningFailed,
  564. .customEvaluationFailed:
  565. return nil
  566. }
  567. }
  568. var underlyingError: Error? {
  569. switch self {
  570. case let .customEvaluationFailed(error):
  571. return error
  572. case let .trustEvaluationFailed(error):
  573. return error
  574. case .noRequiredEvaluator,
  575. .noCertificatesFound,
  576. .noPublicKeysFound,
  577. .policyApplicationFailed,
  578. .settingAnchorCertificatesFailed,
  579. .revocationPolicyCreationFailed,
  580. .defaultEvaluationFailed,
  581. .hostValidationFailed,
  582. .revocationCheckFailed,
  583. .certificatePinningFailed,
  584. .publicKeyPinningFailed:
  585. return nil
  586. }
  587. }
  588. }
  589. // MARK: - Error Descriptions
  590. extension AFError: LocalizedError {
  591. public var errorDescription: String? {
  592. switch self {
  593. case .explicitlyCancelled:
  594. return "Request explicitly cancelled."
  595. case let .invalidURL(url):
  596. return "URL is not valid: \(url)"
  597. case let .parameterEncodingFailed(reason):
  598. return reason.localizedDescription
  599. case let .parameterEncoderFailed(reason):
  600. return reason.localizedDescription
  601. case let .multipartEncodingFailed(reason):
  602. return reason.localizedDescription
  603. case let .requestAdaptationFailed(error):
  604. return "Request adaption failed with error: \(error.localizedDescription)"
  605. case let .responseValidationFailed(reason):
  606. return reason.localizedDescription
  607. case let .responseSerializationFailed(reason):
  608. return reason.localizedDescription
  609. case let .requestRetryFailed(retryError, originalError):
  610. return """
  611. Request retry failed with retry error: \(retryError.localizedDescription), \
  612. original error: \(originalError.localizedDescription)
  613. """
  614. case .sessionDeinitialized:
  615. return """
  616. Session was invalidated without error, so it was likely deinitialized unexpectedly. \
  617. Be sure to retain a reference to your Session for the duration of your requests.
  618. """
  619. case let .sessionInvalidated(error):
  620. return "Session was invalidated with error: \(error?.localizedDescription ?? "No description.")"
  621. case let .serverTrustEvaluationFailed(reason):
  622. return "Server trust evaluation failed due to reason: \(reason.localizedDescription)"
  623. case let .urlRequestValidationFailed(reason):
  624. return "URLRequest validation failed due to reason: \(reason.localizedDescription)"
  625. case let .createUploadableFailed(error):
  626. return "Uploadable creation failed with error: \(error.localizedDescription)"
  627. case let .createURLRequestFailed(error):
  628. return "URLRequest creation failed with error: \(error.localizedDescription)"
  629. case let .downloadedFileMoveFailed(error, source, destination):
  630. return "Moving downloaded file from: \(source) to: \(destination) failed with error: \(error.localizedDescription)"
  631. case let .sessionTaskFailed(error):
  632. return "URLSessionTask failed with error: \(error.localizedDescription)"
  633. }
  634. }
  635. }
  636. extension AFError.ParameterEncodingFailureReason {
  637. var localizedDescription: String {
  638. switch self {
  639. case .missingURL:
  640. return "URL request to encode was missing a URL"
  641. case let .jsonEncodingFailed(error):
  642. return "JSON could not be encoded because of error:\n\(error.localizedDescription)"
  643. case let .customEncodingFailed(error):
  644. return "Custom parameter encoder failed with error: \(error.localizedDescription)"
  645. }
  646. }
  647. }
  648. extension AFError.ParameterEncoderFailureReason {
  649. var localizedDescription: String {
  650. switch self {
  651. case let .missingRequiredComponent(component):
  652. return "Encoding failed due to a missing request component: \(component)"
  653. case let .encoderFailed(error):
  654. return "The underlying encoder failed with the error: \(error)"
  655. }
  656. }
  657. }
  658. extension AFError.MultipartEncodingFailureReason {
  659. var localizedDescription: String {
  660. switch self {
  661. case let .bodyPartURLInvalid(url):
  662. return "The URL provided is not a file URL: \(url)"
  663. case let .bodyPartFilenameInvalid(url):
  664. return "The URL provided does not have a valid filename: \(url)"
  665. case let .bodyPartFileNotReachable(url):
  666. return "The URL provided is not reachable: \(url)"
  667. case let .bodyPartFileNotReachableWithError(url, error):
  668. return """
  669. The system returned an error while checking the provided URL for reachability.
  670. URL: \(url)
  671. Error: \(error)
  672. """
  673. case let .bodyPartFileIsDirectory(url):
  674. return "The URL provided is a directory: \(url)"
  675. case let .bodyPartFileSizeNotAvailable(url):
  676. return "Could not fetch the file size from the provided URL: \(url)"
  677. case let .bodyPartFileSizeQueryFailedWithError(url, error):
  678. return """
  679. The system returned an error while attempting to fetch the file size from the provided URL.
  680. URL: \(url)
  681. Error: \(error)
  682. """
  683. case let .bodyPartInputStreamCreationFailed(url):
  684. return "Failed to create an InputStream for the provided URL: \(url)"
  685. case let .outputStreamCreationFailed(url):
  686. return "Failed to create an OutputStream for URL: \(url)"
  687. case let .outputStreamFileAlreadyExists(url):
  688. return "A file already exists at the provided URL: \(url)"
  689. case let .outputStreamURLInvalid(url):
  690. return "The provided OutputStream URL is invalid: \(url)"
  691. case let .outputStreamWriteFailed(error):
  692. return "OutputStream write failed with error: \(error)"
  693. case let .inputStreamReadFailed(error):
  694. return "InputStream read failed with error: \(error)"
  695. }
  696. }
  697. }
  698. extension AFError.ResponseSerializationFailureReason {
  699. var localizedDescription: String {
  700. switch self {
  701. case .inputDataNilOrZeroLength:
  702. return "Response could not be serialized, input data was nil or zero length."
  703. case .inputFileNil:
  704. return "Response could not be serialized, input file was nil."
  705. case let .inputFileReadFailed(url):
  706. return "Response could not be serialized, input file could not be read: \(url)."
  707. case let .stringSerializationFailed(encoding):
  708. return "String could not be serialized with encoding: \(encoding)."
  709. case let .jsonSerializationFailed(error):
  710. return "JSON could not be serialized because of error:\n\(error.localizedDescription)"
  711. case let .invalidEmptyResponse(type):
  712. return """
  713. Empty response could not be serialized to type: \(type). \
  714. Use Empty as the expected type for such responses.
  715. """
  716. case let .decodingFailed(error):
  717. return "Response could not be decoded because of error:\n\(error.localizedDescription)"
  718. case let .customSerializationFailed(error):
  719. return "Custom response serializer failed with error:\n\(error.localizedDescription)"
  720. }
  721. }
  722. }
  723. extension AFError.ResponseValidationFailureReason {
  724. var localizedDescription: String {
  725. switch self {
  726. case .dataFileNil:
  727. return "Response could not be validated, data file was nil."
  728. case let .dataFileReadFailed(url):
  729. return "Response could not be validated, data file could not be read: \(url)."
  730. case let .missingContentType(types):
  731. return """
  732. Response Content-Type was missing and acceptable content types \
  733. (\(types.joined(separator: ","))) do not match "*/*".
  734. """
  735. case let .unacceptableContentType(acceptableTypes, responseType):
  736. return """
  737. Response Content-Type "\(responseType)" does not match any acceptable types: \
  738. \(acceptableTypes.joined(separator: ",")).
  739. """
  740. case let .unacceptableStatusCode(code):
  741. return "Response status code was unacceptable: \(code)."
  742. case let .customValidationFailed(error):
  743. return "Custom response validation failed with error: \(error.localizedDescription)"
  744. }
  745. }
  746. }
  747. extension AFError.ServerTrustFailureReason {
  748. var localizedDescription: String {
  749. switch self {
  750. case let .noRequiredEvaluator(host):
  751. return "A ServerTrustEvaluating value is required for host \(host) but none was found."
  752. case .noCertificatesFound:
  753. return "No certificates were found or provided for evaluation."
  754. case .noPublicKeysFound:
  755. return "No public keys were found or provided for evaluation."
  756. case .policyApplicationFailed:
  757. return "Attempting to set a SecPolicy failed."
  758. case .settingAnchorCertificatesFailed:
  759. return "Attempting to set the provided certificates as anchor certificates failed."
  760. case .revocationPolicyCreationFailed:
  761. return "Attempting to create a revocation policy failed."
  762. case let .trustEvaluationFailed(error):
  763. return "SecTrust evaluation failed with error: \(error?.localizedDescription ?? "None")"
  764. case let .defaultEvaluationFailed(output):
  765. return "Default evaluation failed for host \(output.host)."
  766. case let .hostValidationFailed(output):
  767. return "Host validation failed for host \(output.host)."
  768. case let .revocationCheckFailed(output, _):
  769. return "Revocation check failed for host \(output.host)."
  770. case let .certificatePinningFailed(host, _, _, _):
  771. return "Certificate pinning failed for host \(host)."
  772. case let .publicKeyPinningFailed(host, _, _, _):
  773. return "Public key pinning failed for host \(host)."
  774. case let .customEvaluationFailed(error):
  775. return "Custom trust evaluation failed with error: \(error.localizedDescription)"
  776. }
  777. }
  778. }
  779. extension AFError.URLRequestValidationFailureReason {
  780. var localizedDescription: String {
  781. switch self {
  782. case let .bodyDataInGETRequest(data):
  783. return """
  784. Invalid URLRequest: Requests with GET method cannot have body data:
  785. \(String(decoding: data, as: UTF8.self))
  786. """
  787. }
  788. }
  789. }