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

在Swift中使用JSONDecoder进行错误处理,json,swift,Json,Swift,我正在Swift中使用JSONDecoder(),需要获得更好的错误消息 在调试描述(例如)中,我可以看到类似“给定数据不是有效的JSON”的消息,但我需要知道这是一个错误,而不是一个网络错误(例如) 我试图转换成一个解码错误,但这似乎没有透露更多信息。我当然不需要字符串-即使是错误代码也比这个有用得多…从不打印错误。解码捕获块中的本地化描述。这将返回一条毫无意义的通用错误消息。始终打印错误实例。然后你得到想要的信息 let decoder = JSONDecoder() if let

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

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


我试图转换成一个
解码错误
,但这似乎没有透露更多信息。我当然不需要字符串-即使是错误代码也比这个有用得多…

从不打印
错误。解码
捕获
块中的本地化描述
。这将返回一条毫无意义的通用错误消息。始终打印
错误
实例。然后你得到想要的信息

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)
    }

必须将错误强制转换为特定类型才能访问属性。查看文档了解更多详细信息。我知道,我试过去编码错误。但是它没有比错误更详细的细节。你能发布你尝试过的代码吗?它将帮助我们获得您问题的更多上下文。print(“读取数据时出错”,错误为!DecodingError)print(“错误”,错误为。localizedDescription)let decerr=Error as!DecodingError print(decerr.errorDescription)打印(“ResOn”,decerr.errorDescription)
localizedDescription
仅在需要向最终用户显示某些内容时使用。我非常喜欢这个答案。对于我自己的调试来说,唯一的区别是省略了
上下文
变量,因为它太冗长了
catch let DecodingError.keyNotFound(key,{print(“[!]key'\(key)\'未找到”)
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)
    }