AFError.swift 37 KB

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