使用PromiseKit时如何捕获请求中的错误?

时间:2019-04-08 11:37:51

标签: ios swift promisekit

我已经开始在异步请求中使用PromiseKit,但现在有一个问题,我无法解析链中的错误。 我有一个方法如下的请求管理器:

func request(
        url: String,
        parameters: JSON? = nil,
        requestMethod: HTTPMethod,
        completion: @escaping completion
    ) {
        self.logger.log(category: .network, message: "Starting request", access: .public)
        Alamofire.request(
            url,
            method: requestMethod,
            parameters: parameters,
            encoding: JSONEncoding.prettyPrinted
        ).responseData { response in
            if let data = response.data {
                self.logger.log(category: .network, message: "Response: \(data)", access: .private)
                completion(.success(data))
            } else {
                self.logger.log(category: .network, message: SWError.dataError.localizedDescription, access: .public, type: .error)
                completion(.failure(SWError.dataError))
            }
        }
    }

请求正在这样创建:

public class func getSettings(
        completion: @escaping (Result<Model.Settings.Settings>) -> Void
        ) {
        RequestManager.shared.request(
            url: Endpoint.Settings.slash.url(),
            requestMethod: .get
        ) { result in
            switch result {
            case let .success(data):
                do {
                    let result = try JSONDecoder().decode(Model.Settings.Settings.self, from: data)
                    completion(.success(result))
                } catch {
                    Request.Shared.handleCode(from: data, completion: { serverCode in
                        logger.log(category: .network, message: SWError.decodingError.localizedDescription, access: .public, type: .error)
                        completion(.failure(serverCode))
                    })
                }
            case let .failure(error):
                completion(.failure(error))
            }
        }
    }

承诺部分在这里:

private func getAppSettings() -> Promise<[Model.Settings.Datum]> {
        return Promise { seal in
            Request.Settings.getSettings(completion: { result in
                switch result {
                case let .success(model):
                    if let data = model.data {
                        seal.fulfill(data)
                    } else {
                        seal.reject(SWError.create(with: "No app settings data"))
                    }
                case let .failure(error):
                    seal.reject(error)
                }
            })
        }
    }

以某种方式我无法捕获错误。我的要求出了什么问题?怎么做对了?

1 个答案:

答案 0 :(得分:0)

用Promises替换Request和getSettings中的CompletionHandler。根据我的理解,我对此进行了一定程度的修改。

修改

func request(url: String,
             parameters: JSON? = nil,
             requestMethod: HTTPMethod,
             completion: @escaping completion)

func request(url: String,
             parameters: JSON? = nil,
             requestMethod: HTTPMethod) -> Promise<[Model.Settings.Datum]> {
    return Promise { seal in

    self.logger.log(category: .network, message: "Starting request", access: .public)
    Alamofire.request(
        url,
        method: requestMethod,
        parameters: parameters,
        encoding: JSONEncoding.prettyPrinted
        ).responseData { response in
            if let data = response.data {
                self.logger.log(category: .network, message: "Response: \(data)", access: .private)
                seal.fulfill(data)
            } else {
                self.logger.log(category: .network, message: SWError.dataError.localizedDescription, access: .public, type: .error)
                seal.reject(.failure(SWError.dataError))
            }
        }
    }
}

还要修改

public func getSettings( completion: @escaping (Result<Model.Settings.Settings>) -> Void)

public func getSettings() -> Promise<[Model.Settings.Settings]>  {
    return Promise { seal in

    RequestManager.shared.request(
        url: Endpoint.Settings.slash.url(),
        requestMethod: .get).then { data in
            do {
                let result = try JSONDecoder().decode(Model.Settings.Settings.self, from: data)
                seal.fulfill(result)
            } catch {
                Request.Shared.handleCode(from: data).then { serverCode in
                    logger.log(category: .network, message: SWError.decodingError.localizedDescription, access: .public, type: .error)
                    seal.reject(.failure(serverCode))
                }
            }
    }
}

修改后,在getAppSettings中使用这些方法,以便可以成功捕获错误情况。

func getAppSettings() -> Promise<[Model.Settings.Datum]> {
    return Promise { seal in
        Request.Settings.getSettings.then { model in
            if let data = model.data {
                seal.fulfill(data)
            } else {
                seal.reject(SWError.create(with: "No app settings data"))
            }
        }
    }
}