[在Alamofire请求中使用validate()时如何处理错误?

问题描述 投票:0回答:2

Id喜欢处理状态代码100 ... 402和404 ... 599。 403由AuthInterceptor处理。

我已经尝试删除validate()并由我自己处理,但在请求中没有validate()的情况下不会调用拦截器。

request = AF.request(encodedURLRequest, interceptor: AuthInterceptor()).validate().responseData { (response) in
    ...
}

我需要在该块“ ...”中处理这些状态代码最好的方法是在验证方法中指定不带403的序列100.599。如果可能的话。

swift alamofire
2个回答
0
投票

您可以尝试以下操作

 Alamofire.request(urlRequest,headers:headers).validate()
        .responseJSON {
            response in

            guard response.response?.statusCode != 403 else
            {
               print("Session expired, Must relogin")
                return
            }
            guard response.response?.statusCode != 500 else
            {
                print("Something Went wrong, please refresh")
                return
            }
            guard response.response?.statusCode != 504 else
            {
               Print("Gateway timeout, Please refresh")
                return
            }
            switch response.result {
            case .success:
                do{
                    let marketChart = try JSONDecoder().decode(data.self, from:response.data!)

                    completionHandler(self.array, nil)

                }
                catch {

                    completionHandler(nil, error)
                }
            case .failure(let error):


                print(error.localizedDescription)
                completionHandler(nil, error)
            }
    }

0
投票

为了重试您的请求,您必须在Alamofire的请求管道中的某个时刻产生错误。 validate()自动为您执行此操作,从而在调用响应序列化程序之前重试该请求。您可以自定义validate()以仅关心所需的状态码,也可以创建自定义响应序列化器并在其中抛出错误。您可以使用自己的一组状态码来自定义验证:

lvar allowedStatusCodes = Set(200..<500)
allowedStatusCodes.remove(403)

AF.request(...).validate(statusCode: allowedStatusCodes).response { ... }
© www.soinside.com 2019 - 2024. All rights reserved.