Alamofire:如何全局处理错误

Alamofire : How to handle errors globally

我的问题与这个问题非常相似,但对于 Alamofire:AFNetworking: Handle error globally and repeat request

如何能够全局捕获错误(通常是 401)并在发出其他请求之前处理它(如果不加以管理,最终会失败)?

我曾考虑链接一个自定义响应处理程序,但在应用程序的每个请求上都这样做很愚蠢。
也许 subclassing,但是我应该 subclass 处理哪个 class?

鉴于 NSURLSession 的并行性质,在 oauth 流程中处理 401 响应的刷新非常复杂。我花了相当多的时间来构建一个对我们来说非常有效的内部解决方案。以下是对其实现方式的总体思路的高度概括。

import Foundation
import Alamofire

public class AuthorizationManager: Manager {
    public typealias NetworkSuccessHandler = (AnyObject?) -> Void
    public typealias NetworkFailureHandler = (NSHTTPURLResponse?, AnyObject?, NSError) -> Void

    private typealias CachedTask = (NSHTTPURLResponse?, AnyObject?, NSError?) -> Void

    private var cachedTasks = Array<CachedTask>()
    private var isRefreshing = false

    public func startRequest(
        method method: Alamofire.Method,
        URLString: URLStringConvertible,
        parameters: [String: AnyObject]?,
        encoding: ParameterEncoding,
        success: NetworkSuccessHandler?,
        failure: NetworkFailureHandler?) -> Request?
    {
        let cachedTask: CachedTask = { [weak self] URLResponse, data, error in
            guard let strongSelf = self else { return }

            if let error = error {
                failure?(URLResponse, data, error)
            } else {
                strongSelf.startRequest(
                    method: method,
                    URLString: URLString,
                    parameters: parameters,
                    encoding: encoding,
                    success: success,
                    failure: failure
                )
            }
        }

        if self.isRefreshing {
            self.cachedTasks.append(cachedTask)
            return nil
        }

        // Append your auth tokens here to your parameters

        let request = self.request(method, URLString, parameters: parameters, encoding: encoding)

        request.response { [weak self] request, response, data, error in
            guard let strongSelf = self else { return }

            if let response = response where response.statusCode == 401 {
                strongSelf.cachedTasks.append(cachedTask)
                strongSelf.refreshTokens()
                return
            }

            if let error = error {
                failure?(response, data, error)
            } else {
                success?(data)
            }
        }

        return request
    }

    func refreshTokens() {
        self.isRefreshing = true

        // Make the refresh call and run the following in the success closure to restart the cached tasks

        let cachedTaskCopy = self.cachedTasks
        self.cachedTasks.removeAll()
        cachedTaskCopy.map { [=10=](nil, nil, nil) }

        self.isRefreshing = false
    }
}

这里要记住的最重要的事情是,您不想 运行 为每个返回的 401 都调用刷新。大量请求可以同时竞速。因此,您想对第一个 401 采取行动,并将所有其他请求排队,直到 401 成功。我上面概述的解决方案正是这样做的。任何通过 startRequest 方法启动的数据任务在遇到 401 时都会自动刷新。

在此非常简化的示例中未考虑的其他一些需要注意的重要事项是:

  • 线程安全
  • 保证成功或失败的闭包调用
  • 存储和获取 oauth 令牌
  • 正在解析响应
  • 将解析后的响应转换为适当的类型(泛型)

希望这有助于阐明一些问题。


更新

我们现在发布了 Alamofire 4.0,它添加了 RequestAdapterRequestRetrier 协议,让您可以轻松构建自己的身份验证系统,而无需考虑授权实现细节!有关更多信息,请参阅我们的 README,其中有一个完整示例,说明如何在 OAuth2 系统上将其实施到您的应用程序中。

Full Disclosure: The example in the README is only meant to be used as an example. Please please please do NOT just go and copy-paste the code into a production application.

在 Alamofire 5 中你可以使用 RequestInterceptor 这是我在我的一个项目中对 401 错误的错误处理,我将 EnvironmentInterceptor 传递给它的每个请求如果请求出错,将调用重试函数 并且 adapt 函数可以帮助您为您的请求添加默认值

struct EnvironmentInterceptor: RequestInterceptor {

func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (AFResult<URLRequest>) -> Void) {
    var adaptedRequest = urlRequest
    guard let token = KeychainWrapper.standard.string(forKey: KeychainsKeys.token.rawValue) else {
        completion(.success(adaptedRequest))
        return
    }
    adaptedRequest.setValue("Bearer \(token)", forHTTPHeaderField: HTTPHeaderField.authentication.rawValue)
    completion(.success(adaptedRequest))
}

func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
    if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 {
        //get token

        guard let refreshToken = KeychainWrapper.standard.string(forKey: KeychainsKeys.refreshToken.rawValue) else {
            completion(.doNotRetryWithError(error))
            return
        }

        APIDriverAcountClient.refreshToken(refreshToken: refreshToken) { res in
            switch res {
            case .success(let response):
                let saveAccessToken: Bool = KeychainWrapper.standard.set(response.accessToken, forKey: KeychainsKeys.token.rawValue)
                let saveRefreshToken: Bool = KeychainWrapper.standard.set(response.refreshToken, forKey: KeychainsKeys.refreshToken.rawValue)
                let saveUserId: Bool = KeychainWrapper.standard.set(response.userId, forKey: KeychainsKeys.uId.rawValue)
                print("is accesstoken saved ?: \(saveAccessToken)")
                print("is refreshToken saved ?: \(saveRefreshToken)")
                print("is userID saved ?: \(saveUserId)")
                completion(.retry)
                break
            case .failure(let err):
                //TODO logout
                break

            }

        }
    } else {
        completion(.doNotRetry)
    }
}

你可以像这样使用它:

@discardableResult
private static func performRequest<T: Decodable>(route: ApiDriverTrip, decoder: JSONDecoder = JSONDecoder(), completion: @escaping (AFResult<T>)->Void) -> DataRequest {

    return AF.request(route, interceptor: EnvironmentInterceptor())
        .responseDecodable (decoder: decoder){ (response: DataResponse<T>) in
         completion(response.result)
}