AFError.swift 37 KB

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