如何在 swift 中解析时打印错误消息

How to print error message while parsing in swift

提问人:Swift 提问时间:1/28/2023 最后编辑:Swift 更新时间:1/29/2023 访问量:386

问:

这是 JSON 错误结构:

{
    "jsonrpc": "2.0",
    "error": {
        "code": "-32700",
        "message": "Parse error",
        "meaning": "Could not decode token: Error while decoding to JSON: Syntax error"
    }
}

这是成功响应结构:

{
    "jsonrpc": "2.0",
    "result": {
        "users": [
            {
                "id": 371,..... so on data

这里无法在我的代码中打印错误>消息

code:这里可以在print语句中打印json响应结果或错误字典,但只能打印case .success(_)error > meaning

如何在下面的代码中打印错误,请指导我"Parse error"

class GeneralResponse<T: Codable>: Codable {
    var result: T?
    let error: ErrorClass?
}

struct ErrorClass: Codable {
    let code, message, meaning: String?
}

struct RequestObject {
    var params: [String: AnyObject]? = nil
    var method: HTTPMethod
    var path: String
    var isTokenNeed: Bool = false
    var vc: UIViewController?
}

class NetworkManager {
    
    private let decoder: JSONDecoder
    static let sharedInstance = NetworkManager()
    
    public init(_ decoder: JSONDecoder = JSONDecoder()) {
        self.decoder = decoder
    }
    
    public func serviceCall<T: Codable>(_ objectType: T.Type,
                                        with request: RequestObject,
                                        completion: @escaping  (T?, Error?) -> Void)  {
        
        
        let paramsDict  = ["jsonrpc" : "2.0", "params" : request.params ?? nil] as [String : Any?]
        
        
        AF.request(request.path, method: request.method, parameters: paramsDict as [String : AnyObject], encoding: JSONEncoding.default, headers: "Accept": "application/json")
            .responseJSON { response in
                
                switch response.result {
                case .success(_):
                    do {
                        print("only json respopnse \(response)")
                        
                        let data = response.data
                        let responseData  = try self.decoder.decode(T.self, from: data ?? Data())
                        completion(responseData, nil)
                    } catch {
                        completion(nil, error)
                        print("in catch \(error)")
                    }
                case .failure(let AFError):
                    let error = AFError
                    print(error.localizedDescription)
                    print("failure error: \(error)")
                }
            }
    }
}

使用 print(“only json respopnse \(response)”) 的上述调用中的错误 o/p

only json respopnse success({
error =     {
    code = "-32700";
    meaning = "Token Signature could not be verified.";
    message = "Parse error";
};
jsonrpc = "2.0";
})

编辑2:此处成功响应未出现在ViewController中

struct PostModel: Codable {
    let jsonrpc: String?
    let result: PostResult?
}
struct PostResult: Codable {
    let users: [PostUser]?
}
struct PostUser: Codable {
    let id: Int?
}

在VC中像这样调用

var k12Data: PostModel?

let paramet = ["location": "", "country": "", "gender": "", "keyword": ""] as [String : AnyObject]

let request = RequestObject(params: paramet, method: .post, path: "https://phpwebdevelopmentserv/", isTokenNeed: true, vc: self)
NetworkManager.sharedInstance.serviceCall(PostModel.self, with: request) { (response, error) in
print("viewcontroller data \(response)")
}

O/P

viewcontroller data 可选(TestigAllInOne.PostModel(jsonrpc: nil, result: nil))

iOS JSON Swift 错误处理 可编码

评论

0赞 burnsi 1/28/2023
请说明您是如何打电话的?serviceCall
0赞 burnsi 1/28/2023
什么?PostModel
0赞 Swift 1/28/2023
@burnsi,我需要处理类中的错误,而不是在viewcontroller中NetworkManager
0赞 Swift 1/28/2023
@burnsi,使用 app.quicktype.io 创建的 API json 响应模型
1赞 vadian 1/28/2023
最好的方法是将 repsonse with 直接解码为具有关联值的枚举,例如 see stackoverflow.com/questions/60372771/... ,已弃用。而且你不能认真地发送一个UIViewController实例作为参数,参数总是不是。并且已经过时了,要摆脱可选responseDecodableresponseJSON[String:Any][String:AnyObject](T?, Error?)Result<T,Error>

答:

1赞 burnsi 1/28/2023 #1

你没有向我们展示你的,所以我假设它属于某种类型的类别。PostmodelGeneralResponse<T>

应解码为 GeneralResponse 类:

let responseData = try self.decoder.decode(GeneralResponse<T>.self, from: data)

现在,您可以打印错误(如果存在):

print(responseData.error?.meaning ?? "no error")

并像这样调用完成处理程序:

guard let result = responseData.result else{
    // unknown error has occured
    completion(nil, nil) // you probably need to create a custom error here
    return
}

completion(result, nil)

主要的本质是不要将参数传递给您的函数,而是传递您期望的类型。因此,例如,如果您的类型如下所示:GeneralResponseresultUser

struct User: Codable{
    var id: String
}

这样称呼它:

networkmanager.serviceCall([User].self, with: RequestObject(...)) { users, error in
    // users is of type `[User]` here.
}

评论

0赞 Swift 1/28/2023
我已经在我的帖子中添加了...一旦经历了它......在您的答案中,能够打印错误并得到响应,但在 ViewController 中没有得到响应PostModelNetworkManager
0赞 Swift 1/28/2023
networkmanager.serviceCall([User].self,带有:RequestObject(...)){ users, error in // 用户在这里是类型。[User]
0赞 Swift 1/28/2023
这是行不通的。.应更改位置以获得响应
0赞 burnsi 1/28/2023
@Swift什么不起作用。你真的需要更精确。根据你的说法,这应该有效。请添加确切的错误消息。PostModel
0赞 Swift 1/29/2023
我已经在带有输出的帖子部分添加了我的代码。请一次浏览edit 2