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

jjjwad0x  于 2023-01-29  发布在  Swift
关注(0)|答案(1)|浏览(138)

这是json错误结构:

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

这就是成功React结构:

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

这里我无法打印错误〉消息在我代码

**代码:**此处可以在case .success(_)打印语句中打印json响应结果或错误字典,但如何仅打印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)")
                }
            }
    }
}

o/p表示上述调用print("only json respopnse \(response)")时出错

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

在视图控制器中像这样调用上述方法:

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

let request = RequestObject(params: parameter, method: .post, path: "https://phpwebdevelopment/api/new-user", isTokenNeed: true, vc: self)
NetworkManager.sharedInstance.serviceCall(PostModel.self, with: request) { (response, error) in

 }

型号:

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

wnavrhmk1#

你没有给我们看你的Postmodel,所以我假设它是某种类型的GeneralResponse<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)

主要的本质是不要把GeneralResponse作为参数传递给你的函数,而是你所期望的result类型。例如,你的User类型如下所示:

struct User: Codable{
    var id: String
}

这样称呼它:

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

相关问题