如何解码 Alamofire 5 中的错误正文?

人气:814 发布:2022-10-16 标签: alamofire alamofire5

问题描述

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

I'm trying to migrate my project from Alamofire 4.9 to 5.3 and I'm having a hard time with error handling. I would like to use Decodable as much as possible, but my API endpoints return one JSON structure when everything goes well, and a different JSON structure when there is an error, the same for all errors across all endpoints. The corresponding Codable in my code is ApiError.

我想创建一个自定义响应序列化程序,它可以给我一个 Result 而不是默认的 Result.我发现这篇文章 似乎解释了一般过程但是里面的代码不能编译.

I would like to create a custom response serializer that can give me a Result<T, ApiError> instead of the default Result<T, AFError>. I found this article that seems to explain the general process but the code in there does not compile.

如何创建这样的自定义 ResponseSerializer?

How can I create such a custom ResponseSerializer?

推荐答案

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

I ended up making it work with the following 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:

And with that, I can call my API like so:

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 范围之外的任何状态代码都对应于错误.

I simply consider that any status code outside of the 200-299 range corresponds to an error.

608