gpt4 book ai didi

json - 在 Swift 中使用 JSONDecoder 进行错误处理

转载 作者:行者123 更新时间:2023-12-03 09:23:29 25 4
gpt4 key购买 nike

我正在使用 JSONDecoder()在 Swift 中,需要获得更好的错误消息。

在调试描述中(例如),我可以看到“给定的数据不是有效的 JSON”之类的消息,但我需要知道它是那个而不是网络错误(例如)。

    let decoder = JSONDecoder()
if let data = data{
do {
// process data

} catch let error {
// can access error.localizedDescription but seemingly nothing else
}

我试图转换到 DecodingError ,但这似乎并没有透露更多信息。我当然不需要字符串 - 即使是错误代码也比这更有帮助......

最佳答案

从不 打印 error.localizedDescription在解码中 catch堵塞。这将返回一个毫无意义的通用错误消息。始终打印 error实例。然后你会得到想要的信息。

let decoder = JSONDecoder()
if let data = data {
do {
// process data

} catch {
print(error)
}

或为 一组错误使用
let decoder = JSONDecoder()
if let data = data {
do {
// process data
} catch let DecodingError.dataCorrupted(context) {
print(context)
} catch let DecodingError.keyNotFound(key, context) {
print("Key '\(key)' not found:", context.debugDescription)
print("codingPath:", context.codingPath)
} catch let DecodingError.valueNotFound(value, context) {
print("Value '\(value)' not found:", context.debugDescription)
print("codingPath:", context.codingPath)
} catch let DecodingError.typeMismatch(type, context) {
print("Type '\(type)' mismatch:", context.debugDescription)
print("codingPath:", context.codingPath)
} catch {
print("error: ", error)
}

关于json - 在 Swift 中使用 JSONDecoder 进行错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55389926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com