AFError.swift 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  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. case bodyDataInGETRequest(Data)
  163. }
  164. /// `Request` was explicitly cancelled.
  165. case explicitlyCancelled
  166. /// `URLConvertible` type failed to create a valid `URL`.
  167. case invalidURL(url: URLConvertible)
  168. /// Multipart form encoding failed.
  169. case multipartEncodingFailed(reason: MultipartEncodingFailureReason)
  170. /// `ParameterEncoding` threw an error during the encoding process.
  171. case parameterEncodingFailed(reason: ParameterEncodingFailureReason)
  172. /// `ParameterEncoder` threw an error while running the encoder.
  173. case parameterEncoderFailed(reason: ParameterEncoderFailureReason)
  174. /// `RequestAdapter` threw an error during adaptation.
  175. case requestAdaptationFailed(error: Error)
  176. /// `RequestRetrier` threw an error during the request retry process.
  177. case requestRetryFailed(retryError: Error, originalError: Error)
  178. /// Response validation failed.
  179. case responseValidationFailed(reason: ResponseValidationFailureReason)
  180. /// Response serialization failed.
  181. case responseSerializationFailed(reason: ResponseSerializationFailureReason)
  182. /// `ServerTrustEvaluating` instance threw an error during trust evaluation.
  183. case serverTrustEvaluationFailed(reason: ServerTrustFailureReason)
  184. /// `Session` which issued the `Request` was deinitialized, most likely because its reference went out of scope.
  185. case sessionDeinitialized
  186. /// `Session` was explicitly invalidated, possibly with the `Error` produced by the underlying `URLSession`.
  187. case sessionInvalidated(error: Error?)
  188. /// `URLRequest` failed validation.
  189. case urlRequestValidationFailed(reason: URLRequestValidationFailureReason)
  190. /// `UploadableConvertible` threw an error in `createUploadable()`.
  191. case createUploadableFailed(error: Error)
  192. /// `URLRequestConvertible` threw an error in `asURLRequest()`.
  193. case createURLRequestFailed(error: Error)
  194. /// `SessionDelegate` threw an error while attempting to move downloaded file to destination URL.
  195. case downloadedFileMoveFailed(error: Error, source: URL, destination: URL)
  196. /// `URLSessionTask` completed with error.
  197. case sessionTaskFailed(error: Error)
  198. }
  199. extension Error {
  200. /// Returns the instance cast as an `AFError`.
  201. public var asAFError: AFError? {
  202. return self as? AFError
  203. }
  204. /// Returns the instance cast as an `AFError`. If casting fails, a `fatalError` with the specified `message` is thrown.
  205. public func asAFError(orFailWith message: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> AFError {
  206. guard let afError = self as? AFError else {
  207. fatalError(message(), file: file, line: line)
  208. }
  209. return afError
  210. }
  211. /// Casts the instance as `AFError` or returns `defaultAFError`
  212. func asAFError(or defaultAFError: @autoclosure () -> AFError) -> AFError {
  213. return self as? AFError ?? defaultAFError()
  214. }
  215. }
  216. // MARK: - Error Booleans
  217. extension AFError {
  218. /// Returns whether the instance is `.sessionDeinitialized`.
  219. public var isSessionDeinitializedError: Bool {
  220. if case .sessionDeinitialized = self { return true }
  221. return false
  222. }
  223. /// Returns whether the instance is `.sessionInvalidated`.
  224. public var isSessionInvalidatedError: Bool {
  225. if case .sessionInvalidated = self { return true }
  226. return false
  227. }
  228. /// Returns whether the instance is `.explicitlyCancelled`.
  229. public var isExplicitlyCancelledError: Bool {
  230. if case .explicitlyCancelled = self { return true }
  231. return false
  232. }
  233. /// Returns whether the instance is `.invalidURL`.
  234. public var isInvalidURLError: Bool {
  235. if case .invalidURL = self { return true }
  236. return false
  237. }
  238. /// Returns whether the instance is `.parameterEncodingFailed`. When `true`, the `underlyingError` property will
  239. /// contain the associated value.
  240. public var isParameterEncodingError: Bool {
  241. if case .parameterEncodingFailed = self { return true }
  242. return false
  243. }
  244. /// Returns whether the instance is `.parameterEncoderFailed`. When `true`, the `underlyingError` property will
  245. /// contain the associated value.
  246. public var isParameterEncoderError: Bool {
  247. if case .parameterEncoderFailed = self { return true }
  248. return false
  249. }
  250. /// Returns whether the instance is `.multipartEncodingFailed`. When `true`, the `url` and `underlyingError`
  251. /// properties will contain the associated values.
  252. public var isMultipartEncodingError: Bool {
  253. if case .multipartEncodingFailed = self { return true }
  254. return false
  255. }
  256. /// Returns whether the instance is `.requestAdaptationFailed`. When `true`, the `underlyingError` property will
  257. /// contain the associated value.
  258. public var isRequestAdaptationError: Bool {
  259. if case .requestAdaptationFailed = self { return true }
  260. return false
  261. }
  262. /// Returns whether the instance is `.responseValidationFailed`. When `true`, the `acceptableContentTypes`,
  263. /// `responseContentType`, `responseCode`, and `underlyingError` properties will contain the associated values.
  264. public var isResponseValidationError: Bool {
  265. if case .responseValidationFailed = self { return true }
  266. return false
  267. }
  268. /// Returns whether the instance is `.responseSerializationFailed`. When `true`, the `failedStringEncoding` and
  269. /// `underlyingError` properties will contain the associated values.
  270. public var isResponseSerializationError: Bool {
  271. if case .responseSerializationFailed = self { return true }
  272. return false
  273. }
  274. /// Returns whether the instance is `.serverTrustEvaluationFailed`. When `true`, the `underlyingError` property will
  275. /// contain the associated value.
  276. public var isServerTrustEvaluationError: Bool {
  277. if case .serverTrustEvaluationFailed = self { return true }
  278. return false
  279. }
  280. /// Returns whether the instance is `requestRetryFailed`. When `true`, the `underlyingError` property will
  281. /// contain the associated value.
  282. public var isRequestRetryError: Bool {
  283. if case .requestRetryFailed = self { return true }
  284. return false
  285. }
  286. /// Returns whether the instance is `createUploadableFailed`. When `true`, the `underlyingError` property will
  287. /// contain the associated value.
  288. public var isCreateUploadableError: Bool {
  289. if case .createUploadableFailed = self { return true }
  290. return false
  291. }
  292. /// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will
  293. /// contain the associated value.
  294. public var isCreateURLRequestError: Bool {
  295. if case .createURLRequestFailed = self { return true }
  296. return false
  297. }
  298. /// Returns whether the instance is `downloadedFileMoveFailed`. When `true`, the `destination` and `underlyingError` properties will
  299. /// contain the associated values.
  300. public var isDownloadedFileMoveError: Bool {
  301. if case .downloadedFileMoveFailed = self { return true }
  302. return false
  303. }
  304. /// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will
  305. /// contain the associated value.
  306. public var isSessionTaskError: Bool {
  307. if case .sessionTaskFailed = self { return true }
  308. return false
  309. }
  310. }
  311. // MARK: - Convenience Properties
  312. extension AFError {
  313. /// The `URLConvertible` associated with the error.
  314. public var urlConvertible: URLConvertible? {
  315. guard case .invalidURL(let url) = self else { return nil }
  316. return url
  317. }
  318. /// The `URL` associated with the error.
  319. public var url: URL? {
  320. guard case .multipartEncodingFailed(let reason) = self else { return nil }
  321. return reason.url
  322. }
  323. /// The underlying `Error` responsible for generating the failure associated with `.sessionInvalidated`,
  324. /// `.parameterEncodingFailed`, `.parameterEncoderFailed`, `.multipartEncodingFailed`, `.requestAdaptationFailed`,
  325. /// `.responseSerializationFailed`, `.requestRetryFailed` errors.
  326. public var underlyingError: Error? {
  327. switch self {
  328. case .multipartEncodingFailed(let reason):
  329. return reason.underlyingError
  330. case .parameterEncodingFailed(let reason):
  331. return reason.underlyingError
  332. case .parameterEncoderFailed(let reason):
  333. return reason.underlyingError
  334. case .requestAdaptationFailed(let error):
  335. return error
  336. case .requestRetryFailed(let retryError, _):
  337. return retryError
  338. case .responseValidationFailed(let reason):
  339. return reason.underlyingError
  340. case .responseSerializationFailed(let reason):
  341. return reason.underlyingError
  342. case .serverTrustEvaluationFailed(let reason):
  343. return reason.underlyingError
  344. case .sessionInvalidated(let error):
  345. return error
  346. case .urlRequestValidationFailed(let reason):
  347. return reason.underlyingError
  348. case .createUploadableFailed(let error):
  349. return error
  350. case .createURLRequestFailed(let error):
  351. return error
  352. case .downloadedFileMoveFailed(let error, _, _):
  353. return error
  354. case .sessionTaskFailed(let error):
  355. return error
  356. case .explicitlyCancelled,
  357. .invalidURL(_),
  358. .sessionDeinitialized:
  359. return nil
  360. }
  361. }
  362. /// The acceptable `Content-Type`s of a `.responseValidationFailed` error.
  363. public var acceptableContentTypes: [String]? {
  364. guard case .responseValidationFailed(let 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 .responseValidationFailed(let 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 .responseValidationFailed(let 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 .responseSerializationFailed(let 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 .downloadedFileMoveFailed(_, let 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 .downloadedFileMoveFailed(_, _, let destination) = self else { return nil }
  390. return destination
  391. }
  392. }
  393. extension AFError.ParameterEncodingFailureReason {
  394. var underlyingError: Error? {
  395. switch self {
  396. case .jsonEncodingFailed(let error),
  397. .customEncodingFailed(let 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 .encoderFailed(let 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 .bodyPartURLInvalid(let url),
  418. .bodyPartFilenameInvalid(let url),
  419. .bodyPartFileNotReachable(let url),
  420. .bodyPartFileIsDirectory(let url),
  421. .bodyPartFileSizeNotAvailable(let url),
  422. .bodyPartInputStreamCreationFailed(let url),
  423. .outputStreamCreationFailed(let url),
  424. .outputStreamFileAlreadyExists(let url),
  425. .outputStreamURLInvalid(let url),
  426. .bodyPartFileNotReachableWithError(let url, _),
  427. .bodyPartFileSizeQueryFailedWithError(let url, _):
  428. return url
  429. case .outputStreamWriteFailed(_),
  430. .inputStreamReadFailed(_):
  431. return nil
  432. }
  433. }
  434. var underlyingError: Error? {
  435. switch self {
  436. case .bodyPartFileNotReachableWithError(_, let error),
  437. .bodyPartFileSizeQueryFailedWithError(_, let error),
  438. .outputStreamWriteFailed(let error),
  439. .inputStreamReadFailed(let 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 .missingContentType(let types),
  458. .unacceptableContentType(let 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 .unacceptableContentType(_, let 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 .unacceptableStatusCode(let 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 .customValidationFailed(let 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 .stringSerializationFailed(let 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 .jsonSerializationFailed(let error),
  522. .decodingFailed(let error),
  523. .customSerializationFailed(let 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 .defaultEvaluationFailed(let output),
  538. .hostValidationFailed(let output),
  539. .revocationCheckFailed(let 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 .customEvaluationFailed(let 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. extension AFError.URLRequestValidationFailureReason {
  573. var underlyingError: Error? {
  574. switch self {
  575. case .bodyDataInGETRequest(_):
  576. return nil
  577. }
  578. }
  579. }
  580. // MARK: - Error Descriptions
  581. extension AFError: LocalizedError {
  582. public var errorDescription: String? {
  583. switch self {
  584. case .explicitlyCancelled:
  585. return "Request explicitly cancelled."
  586. case .invalidURL(let url):
  587. return "URL is not valid: \(url)"
  588. case .parameterEncodingFailed(let reason):
  589. return reason.localizedDescription
  590. case .parameterEncoderFailed(let reason):
  591. return reason.localizedDescription
  592. case .multipartEncodingFailed(let reason):
  593. return reason.localizedDescription
  594. case .requestAdaptationFailed(let error):
  595. return "Request adaption failed with error: \(error.localizedDescription)"
  596. case .responseValidationFailed(let reason):
  597. return reason.localizedDescription
  598. case .responseSerializationFailed(let reason):
  599. return reason.localizedDescription
  600. case .requestRetryFailed(let retryError, let originalError):
  601. return """
  602. Request retry failed with retry error: \(retryError.localizedDescription), \
  603. original error: \(originalError.localizedDescription)
  604. """
  605. case .sessionDeinitialized:
  606. return """
  607. Session was invalidated without error, so it was likely deinitialized unexpectedly. \
  608. Be sure to retain a reference to your Session for the duration of your requests.
  609. """
  610. case .sessionInvalidated(let error):
  611. return "Session was invalidated with error: \(error?.localizedDescription ?? "No description.")"
  612. case .serverTrustEvaluationFailed:
  613. return "Server trust evaluation failed."
  614. case .urlRequestValidationFailed(let reason):
  615. return "URLRequest validation failed due to reason: \(reason.localizedDescription)"
  616. case .createUploadableFailed(let error):
  617. return "Uploadable creation failed with error: \(error.localizedDescription)"
  618. case .createURLRequestFailed(let error):
  619. return "URLRequest creation failed with error: \(error.localizedDescription)"
  620. case .downloadedFileMoveFailed(let error, let source, let destination):
  621. return """
  622. Moving downloaded file failed
  623. from: \(source)
  624. to: \(destination)
  625. error: \(error.localizedDescription)
  626. """
  627. case .sessionTaskFailed(let error):
  628. return "URLSessionTask failed with error: \(error.localizedDescription)"
  629. }
  630. }
  631. }
  632. extension AFError.ParameterEncodingFailureReason {
  633. var localizedDescription: String {
  634. switch self {
  635. case .missingURL:
  636. return "URL request to encode was missing a URL"
  637. case .jsonEncodingFailed(let error):
  638. return "JSON could not be encoded because of error:\n\(error.localizedDescription)"
  639. case .customEncodingFailed(let error):
  640. return "Custom parameter encoder failed with error: \(error.localizedDescription)"
  641. }
  642. }
  643. }
  644. extension AFError.ParameterEncoderFailureReason {
  645. var localizedDescription: String {
  646. switch self {
  647. case .missingRequiredComponent(let component):
  648. return "Encoding failed due to a missing request component: \(component)"
  649. case .encoderFailed(let error):
  650. return "The underlying encoder failed with the error: \(error)"
  651. }
  652. }
  653. }
  654. extension AFError.MultipartEncodingFailureReason {
  655. var localizedDescription: String {
  656. switch self {
  657. case .bodyPartURLInvalid(let url):
  658. return "The URL provided is not a file URL: \(url)"
  659. case .bodyPartFilenameInvalid(let url):
  660. return "The URL provided does not have a valid filename: \(url)"
  661. case .bodyPartFileNotReachable(let url):
  662. return "The URL provided is not reachable: \(url)"
  663. case .bodyPartFileNotReachableWithError(let url, let error):
  664. return (
  665. "The system returned an error while checking the provided URL for " +
  666. "reachability.\nURL: \(url)\nError: \(error)"
  667. )
  668. case .bodyPartFileIsDirectory(let url):
  669. return "The URL provided is a directory: \(url)"
  670. case .bodyPartFileSizeNotAvailable(let url):
  671. return "Could not fetch the file size from the provided URL: \(url)"
  672. case .bodyPartFileSizeQueryFailedWithError(let url, let error):
  673. return (
  674. "The system returned an error while attempting to fetch the file size from the " +
  675. "provided URL.\nURL: \(url)\nError: \(error)"
  676. )
  677. case .bodyPartInputStreamCreationFailed(let url):
  678. return "Failed to create an InputStream for the provided URL: \(url)"
  679. case .outputStreamCreationFailed(let url):
  680. return "Failed to create an OutputStream for URL: \(url)"
  681. case .outputStreamFileAlreadyExists(let url):
  682. return "A file already exists at the provided URL: \(url)"
  683. case .outputStreamURLInvalid(let url):
  684. return "The provided OutputStream URL is invalid: \(url)"
  685. case .outputStreamWriteFailed(let error):
  686. return "OutputStream write failed with error: \(error)"
  687. case .inputStreamReadFailed(let error):
  688. return "InputStream read failed with error: \(error)"
  689. }
  690. }
  691. }
  692. extension AFError.ResponseSerializationFailureReason {
  693. var localizedDescription: String {
  694. switch self {
  695. case .inputDataNilOrZeroLength:
  696. return "Response could not be serialized, input data was nil or zero length."
  697. case .inputFileNil:
  698. return "Response could not be serialized, input file was nil."
  699. case .inputFileReadFailed(let url):
  700. return "Response could not be serialized, input file could not be read: \(url)."
  701. case .stringSerializationFailed(let encoding):
  702. return "String could not be serialized with encoding: \(encoding)."
  703. case .jsonSerializationFailed(let error):
  704. return "JSON could not be serialized because of error:\n\(error.localizedDescription)"
  705. case .invalidEmptyResponse(let type):
  706. return "Empty response could not be serialized to type: \(type). Use Empty as the expected type for such responses."
  707. case .decodingFailed(let error):
  708. return "Response could not be decoded because of error:\n\(error.localizedDescription)"
  709. case .customSerializationFailed(let error):
  710. return "Custom response serializer failed with error:\n\(error.localizedDescription)"
  711. }
  712. }
  713. }
  714. extension AFError.ResponseValidationFailureReason {
  715. var localizedDescription: String {
  716. switch self {
  717. case .dataFileNil:
  718. return "Response could not be validated, data file was nil."
  719. case .dataFileReadFailed(let url):
  720. return "Response could not be validated, data file could not be read: \(url)."
  721. case .missingContentType(let types):
  722. return (
  723. "Response Content-Type was missing and acceptable content types " +
  724. "(\(types.joined(separator: ","))) do not match \"*/*\"."
  725. )
  726. case .unacceptableContentType(let acceptableTypes, let responseType):
  727. return (
  728. "Response Content-Type \"\(responseType)\" does not match any acceptable types: " +
  729. "\(acceptableTypes.joined(separator: ","))."
  730. )
  731. case .unacceptableStatusCode(let code):
  732. return "Response status code was unacceptable: \(code)."
  733. case .customValidationFailed(let error):
  734. return "Custom response validation failed with error: \(error.localizedDescription)"
  735. }
  736. }
  737. }
  738. extension AFError.ServerTrustFailureReason {
  739. var localizedDescription: String {
  740. switch self {
  741. case .noRequiredEvaluator(let host):
  742. return "A ServerTrustEvaluating value is required for host \(host) but none was found."
  743. case .noCertificatesFound:
  744. return "No certificates were found or provided for evaluation."
  745. case .noPublicKeysFound:
  746. return "No public keys were found or provided for evaluation."
  747. case .policyApplicationFailed:
  748. return "Attempting to set a SecPolicy failed."
  749. case .settingAnchorCertificatesFailed:
  750. return "Attempting to set the provided certificates as anchor certificates failed."
  751. case .revocationPolicyCreationFailed:
  752. return "Attempting to create a revocation policy failed."
  753. case .defaultEvaluationFailed(let output):
  754. return "Default evaluation failed for host \(output.host)."
  755. case .hostValidationFailed(let output):
  756. return "Host validation failed for host \(output.host)."
  757. case .revocationCheckFailed(let output, _):
  758. return "Revocation check failed for host \(output.host)."
  759. case .certificatePinningFailed(let host, _, _, _):
  760. return "Certificate pinning failed for host \(host)."
  761. case .publicKeyPinningFailed(let host, _, _, _):
  762. return "Public key pinning failed for host \(host)."
  763. case .customEvaluationFailed(let error):
  764. return "Custom trust evaluation failed with error: \(error.localizedDescription)"
  765. }
  766. }
  767. }
  768. extension AFError.URLRequestValidationFailureReason {
  769. var localizedDescription: String {
  770. switch self {
  771. case .bodyDataInGETRequest(let data):
  772. return """
  773. Invalid URLRequest with a GET method that had body data:
  774. \(String(decoding: data, as: UTF8.self))
  775. """
  776. }
  777. }
  778. }