AFError.swift 36 KB

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