简体   繁体   English

如何从 AFError 中确定特定的 409 错误?

[英]how to determine the specific 409 error from an AFError?

I have a method that returns a Single<(HTTPURLResponse, Any)> doing a call to a webservice.我有一个方法返回一个Single<(HTTPURLResponse, Any)>调用 web 服务。

This call returns an 409 for multiple reasons and this reason is passed as a JSON in the response.由于多种原因,此调用返回 409,并且此原因在响应中作为 JSON 传递。 I know the JSON is in the data attribute of the DataResponse object but I would like to have it in the AFError that I pass when an error occurs.我知道 JSON 位于 DataResponse 对象的 data 属性中,但我希望它位于发生错误时传递的 AFError 中。 I want to display the specific 409 error message related to the JSON response to the user to allow him understand what happened.我想向用户显示与 JSON 响应相关的特定 409 错误消息,让他了解发生了什么。

How could I do that ?我怎么能那样做?

I searched for that in Stackoverflow and also on the github of Alamofire but couldn't find any help to my case.我在 Stackoverflow 和 Alamofire 的 github 中搜索了它,但找不到对我的案例有任何帮助。

return Single<(HTTPURLResponse, Any)>.create(subscribe: { single in
    let request = self.sessionManager.request(completeURL, method: httpMethod, parameters: params, encoding: encoding, headers: headers)
    request.validate().responseJSON(completionHandler: { (response) in
        let result = response.result
        switch result {

        case let .success(value): single(.success((response.response!, value)))
        case let .failure(error): single(.error(error))
        }
    })

    return Disposables.create { request.cancel() }
})

I'm working with Alamofire 4.9.1我正在使用 Alamofire 4.9.1

 request.validate().responseJSON { (response) in


        let statusCode = response.response?.statusCode ?? 0

        guard statusCode !=  409 else {

            if let data = response.data, let errorJson = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                let errorMessage = errorJson["message"] as? String
                let customError = CustomError(message: errorMessage)
                single(.error(customError))
            }


            return
        }


        let result = response.result

        switch result {
        case let .success(value): single(.success((response.response!, value)))
        case let .failure(error): single(.error(error))
        }
    }

I guess you can achieve your requirement by this way.我想你可以通过这种方式实现你的要求。 create a custom Error class to pass the error to completion.创建一个自定义 Error 类以将错误传递到完成。 dont forget to call completion if errorJson is not serialised.如果 errorJson 未序列化,请不要忘记调用完成。

class CustomError: Error {

var localizedDescription: String { message ?? "" }

var message: String?

init(message: String?) {
    self.message = message
}

} }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Alamofire+Combine:如何从 AFError 中获取自定义错误类型 - Alamofire+Combine: how to get custom error type out of AFError 我如何将服务器错误消息转换为 AFError - how can i cast server error message to AFError 错误:可选(Alamofire.AFError.invalidURL(“”)) - Error: Optional(Alamofire.AFError.invalidURL(“”)) Alamofire 错误:“结果”类型的值<any, aferror> '没有成员'值'</any,> - Alamofire Error: Value of type 'Result<Any, AFError>' has no member 'value' Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(错误域=NSCocoaErrorDomain 代码=3840 - Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 操作无法完成。 (Alamofire.AFError 错误 9。) - The operation could not complete. (Alamofire.AFError error 9.) 从 'AFError?' 到不相关的类型 'URLError' 总是失败警告 - Cast from 'AFError?' to unrelated type 'URLError' always fails warning iOS上的phonegap中的Couchbase lite中的409 HTTP错误 - 409 http error in Couchbase lite in phonegap on iOS 在 iOS swift 中滚动时如何确定滚动到达特定位置(我必须确定底部的空间应该是 56 px) - How to determine that the scroll reached to specific position(I have to determine the space from bottom should be 56 px) while scrolling in iOS swift 如何确定来自 Swift.Result 和 Enum 的错误响应 - How to determine Error response from Swift.Result and Enum
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM