使用JSONDecoder处理Swift中的错误

26

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

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

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

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

我尝试将其转换为DecodingError,但这似乎并没有提供更多信息。我肯定不需要字符串 - 即使错误代码比这更有帮助...


你必须将错误转换为特定类型才能访问属性。请查看文档以获取更多详细信息。https://docs.swift.org/swift-book/LanguageGuide/ErrorHandling.html - Aks
我知道,我尝试过DecodingError。但它没有比错误本身更多的细节。 - WishIHadThreeGuns
你能贴出你尝试过的代码吗?这将帮助我们更好地了解你所遇到问题的背景。 - Aks
print ("读取数据错误", error as! DecodingError) print ("错误", error.localizedDescription) let decerr = error as! DecodingError print (decerr.errorDescription) print ("原因", decerr.errorDescription) - WishIHadThreeGuns
1个回答

99
永远不要在解码的catch块中打印error.localizedDescription,因为这会返回一个非常含糊的通用错误信息。始终打印错误实例(error instance),这样你就可以获得所需的信息。
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)
    }
}

2
localizedDescription 只应在需要向最终用户显示内容时使用。 - Peter Schorn
1
我真的很喜欢这个答案。唯一的区别是为了我的调试,省略了context变量,因为它太冗长了。catch let DecodingError.keyNotFound(key, _) { print("[!]Key '\(key)' not found") - rustyMagnet
您能访问类型不匹配的属性吗?比如说一个字段返回的是整型而我期望它是字符串,我希望在这种情况下为该属性设置默认值。 - infiltratingtree
@infiltratingtree 这没有意义,因为当出现错误时,解码过程将被中断和终止。 - vadian
也许我没有解释清楚。我想知道是哪个字段导致了解码错误。有没有办法获取这些信息? - infiltratingtree
该错误显示了代码路径以及预期类型和实际类型。 - vadian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接