2

我正在尝试将我的项目从 Alamofire 4.9 迁移到 5.3,但我很难处理错误。我想Decodable尽可能多地使用,但是当一切顺利时,我的 API 端点返回一个 JSON 结构,当出现错误时返回一个不同的 JSON 结构,所有端点的所有错误都相同。Codable我的代码中对应的是ApiError.

我想创建一个自定义响应序列化程序,它可以给我一个Result<T, ApiError>而不是默认的Result<T, AFError>. 我发现这篇文章似乎解释了一般过程,但其中的代码无法编译。

我怎样才能创建这样的自定义ResponseSerializer

4

2 回答 2

3

我最终使它与以下 ResponseSerializer 一起工作:

struct APIError: Error, Decodable {
    let message: String
    let code: String
    let args: [String]
}

final class TwoDecodableResponseSerializer<T: Decodable>: ResponseSerializer {
    
    lazy var decoder: JSONDecoder = {
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .iso8601
        return decoder
    }()

    private lazy var successSerializer = DecodableResponseSerializer<T>(decoder: decoder)
    private lazy var errorSerializer = DecodableResponseSerializer<APIError>(decoder: decoder)

    public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Result<T, APIError> {

        guard error == nil else { return .failure(APIError(message: "Unknown error", code: "unknown", args: [])) }

        guard let response = response else { return .failure(APIError(message: "Empty response", code: "empty_response", args: [])) }

        do {
            if response.statusCode < 200 || response.statusCode >= 300 {
                let result = try errorSerializer.serialize(request: request, response: response, data: data, error: nil)
                return .failure(result)
            } else {
                let result = try successSerializer.serialize(request: request, response: response, data: data, error: nil)
                return .success(result)
            }
        } catch(let err) {
            return .failure(APIError(message: "Could not serialize body", code: "unserializable_body", args: [String(data: data!, encoding: .utf8)!, err.localizedDescription]))
        }

    }

}

extension DataRequest {
    @discardableResult func responseTwoDecodable<T: Decodable>(queue: DispatchQueue = DispatchQueue.global(qos: .userInitiated), of t: T.Type, completionHandler: @escaping (Result<T, APIError>) -> Void) -> Self {
        return response(queue: .main, responseSerializer: TwoDecodableResponseSerializer<T>()) { response in
            switch response.result {
            case .success(let result):
                completionHandler(result)
            case .failure(let error):
                completionHandler(.failure(APIError(message: "Other error", code: "other", args: [error.localizedDescription])))
            }
        }
    }
}

有了这个,我可以像这样调用我的 API:

AF.request(request).validate().responseTwoDecodable(of: [Item].self) { response in
            switch response {
            case .success(let items):
                completion(.success(items))
            case .failure(let error): //error is an APIError
                log.error("Error while loading items: \(String(describing: error))")
                completion(.failure(.couldNotLoad(underlyingError: error)))
            }
        }

我只是认为 200-299 范围之外的任何状态代码都对应一个错误。

于 2020-10-28T14:06:19.823 回答
0

ResponseSerializers 有一个要求。在很大程度上,您可以复制现有的序列化程序。例如,如果您想解析 CSV(不检查响应):

struct CommaDelimitedSerializer: ResponseSerializer {
    func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> [String] {
        // Call the existing StringResponseSerializer to get many behaviors automatically.
        let string = try StringResponseSerializer().serialize(request: request, 
                                                              response: response, 
                                                              data: data, 
                                                              error: error)
        
        return Array(string.split(separator: ","))
    }
}

您可以在Alamofire 的文档中阅读更多内容。

于 2020-10-27T16:12:31.637 回答