AFError.swift 35 KB

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