当可编码问题发生时,我如何获取 codingPath?

How I can fetch codingPath when codable issue happens?

提问人:János 提问时间:2/16/2023 最后编辑:Joakim DanielsonJános 更新时间:2/17/2023 访问量:50

问:

我试过了这个,但它引发了一个错误:

do {
            guard let firstValue = result.values.first else {
                completion?(nil, NSError(domain: "MyDomain", code: 1, userInfo: [NSLocalizedDescriptionKey: "No first value found"]))
                return
            }
            let jsonData = try JSONSerialization.data(withJSONObject: firstValue, options: [])
            let jsonStr = String(data: jsonData, encoding: .utf8)
            //print(jsonStr!)
            let decoder = JSONDecoder()
            let decodedObject = try decoder.decode(T.self, from: jsonData)
            completion?(decodedObject, nil)
        } catch let decodingError as DecodingError {
            print("Failed to decode JSON: \(decodingError)")
            if let context = decodingError.context { // <----- HERE
                print("Coding path: \(context.codingPath)")
            }
        } catch let error {
            print("An error occurred: \(error)")
            // handle the error here
        }

表达式类型不明确,没有更多上下文

可编码 的快速 错误处理

评论


答:

0赞 Leo Dabus 2/16/2023 #1

扩展 Joakim 帖子 如果你想在你的帖子中使用语法,你可以按如下方式扩展枚举:DecodingError

extension DecodingError {

    var context: Context {
        let context: Context
        switch self {
        case let .dataCorrupted(ctxt):
            context = ctxt
        case let .keyNotFound(_, ctxt):
            context = ctxt
        case let .typeMismatch(_, ctxt):
            context = ctxt
        case let .valueNotFound(_, ctxt):
            context = ctxt
        @unknown default:
            fatalError()
        }
        return context
    }

    var codingPath: [CodingKey] {
       context.codingPath
    }

    var underlyingError: Error? {
        context.underlyingError
    }
}