简体   繁体   English

自定义验证错误不再在 Alamofire 5 中起作用

[英]Custom validation error no longer working in Alamofire 5

Using Alamofire 4, we had an API response validator in place we invoked like so:使用 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
}

It looks like this:它看起来像这样:

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())
}

The appropriate error would make it back to the request completion handler,适当的错误会返回到请求完成处理程序,

▿ APIError
  ▿ appTimeSettingInvalid

and we could update the UI with the right error, everyone was happy.我们可以用正确的错误更新 UI,每个人都很高兴。

But now with Alamofire, it's this:但现在有了 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

Which I need to access like this:我需要像这样访问:

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)
}

This seems absurd.这似乎很荒谬。 What am I missing?我错过了什么? Why did the custom validation fail when nothing has changed about the method, and why is it wrapped in a layer of other errors?当方法没有任何改变时,为什么自定义验证会失败,为什么它会包裹在一层其他错误中? Why retry a request when the validation is going to fail the same way?当验证将以同样的方式失败时,为什么要重试请求?

How do I get my custom error back, consistently, across all my requests?如何在所有请求中始终如一地恢复我的自定义错误?

In Alamofire 5, all errors are returned contained in an AFError instance, including custom validation errors.在 Alamofire 5 中,返回的所有错误都包含在AFError实例中,包括自定义验证错误。 This allows our Response types to contain typed errors and provides a consistent error type.这允许我们的Response类型包含类型错误并提供一致的错误类型。 However, the validation API still returns Error instances, unfortunately, so there is an additional layer to peel back.然而,不幸的是,验证 API 仍然返回Error实例,因此还有一个额外的层可以剥离。 You can use the convenience asAFError property to perform the cast and the underlyingError property to grab any underlying errors.您可以使用便捷的asAFError属性来执行强制转换,并使用underlyingError错误属性来获取任何底层错误。 Use of switch statements can also make the extraction easier.使用switch语句还可以使提取更容易。 You can also mapError on responses to extract the specific error types you want.您还可以在响应上mapError以提取所需的特定错误类型。

As for retry, it's likely your retrier hasn't been updated to extract the errors in such a way that retry is properly avoided with your custom error type.至于重试,很可能您的重试器尚未更新以提取错误,因此您的自定义错误类型可以正确避免重试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM