自定义验证错误在AlamoFire 5中不再有效

人气:262 发布:2022-10-16 标签: xcode swift alamofire alamofire5

问题描述

使用AlamoFire 4,我们有一个API响应验证器,我们按如下方式调用:

func request<Endpoint: APIEndpoint>(_ baseURL: URL, endpoint: Endpoint, completion: @escaping (_ object: Endpoint.ResponseType?, _ error: AFError?) -> Void) -> DataRequest where Endpoint.ResponseType: Codable {
    let responseSerializer = APIObjectResponseSerializer(endpoint)
    let request = self.request(baseURL, endpoint: endpoint)
        .validate(APIResponseValidator.validate)                << VALIDATOR PASSED HERE
        .response(responseSerializer: responseSerializer) { response in
            completion(response.value, response.error)
    }
    return request
}

如下所示:

static func validate(request: URLRequest?, response: HTTPURLResponse, data: Data?) -> Request.ValidationResult {
    // **INSERT OTHER FAILURE CHECKS HERE**

    // Verify server time is within a valid time window.
    let headers = response.allHeaderFields
    guard let serverTimeString = headers["Date"] as? String, let serverTime = DateUtils.headerDateFormatter().date(from: serverTimeString) else {
        Log.error("APIValidation: no Date in response header")
        return .failure(APIError.appTimeSettingInvalid))
    }

    // **INSERT OTHER FAILURE CHECKS HERE**

    return .success(Void())
}

相应的错误将返回到请求完成处理程序

▿ APIError
  ▿ appTimeSettingInvalid

我们可以使用正确的错误更新UI,每个人都很高兴。

但现在有了Alamofire,它是这样的:

▿ Optional<Error>
 ▿ some : AFError
  ▿ requestRetryFailed : 2 elements
   ▿ retryError : AFError
    ▿ responseValidationFailed : 1 element
     ▿ reason : ResponseValidationFailureReason
      ▿ customValidationFailed : 1 element
       ▿ error : APIError
        ▿ appTimeSettingInvalid      << Original custom error
   ▿ originalError : AFError
    ▿ responseValidationFailed : 1 element
      ▿ reason : ResponseValidationFailureReason
       ▿ customValidationFailed : 1 element
        ▿ error : APIError
         ▿ appTimeSettingInvalid      << Original custom error

我需要这样访问:

if let underlyingError = (error as? AFError)?.underlyingError as? AFError,
    case let AFError.requestRetryFailed(_, originalError) = underlyingError,
    case let AFError.responseValidationFailed(reason) = originalError,
    case let .customValidationFailed(initialCustomError) = reason {
    showAlert(initialCustomError)
}

这似乎很荒谬。我遗漏了什么?为什么自定义验证在方法没有任何变化的情况下失败,为什么它被包裹在一层其他错误中?当验证将以同样的方式失败时,为什么要重试请求?

如何跨所有请求一致地取回自定义错误?

推荐答案

在AlamoFire 5中,返回的所有错误都包含在AFError实例中,包括自定义验证错误。这允许我们的Response类型包含类型化错误,并提供一致的错误类型。然而,不幸的是,验证API仍然返回Error实例,因此需要再剥离一层。您可以使用便利性asAFError属性执行强制转换,使用underlyingError属性捕获任何底层错误。使用switch语句也可以简化提取。您还可以对响应mapError提取所需的特定错误类型。

至于重试,您的检索器可能尚未更新,无法以您的自定义错误类型正确避免重试的方式提取错误。

989