在Swift中使用JSONDecoder进行错误处理 [英] Error handling using JSONDecoder in Swift
问题描述
我在Swift中使用JSONDecoder()
,需要获取更好的错误消息.
I am using JSONDecoder()
in Swift and need to get better error messages.
在调试描述中(例如),我可以看到诸如给定数据不是有效的JSON"之类的消息,但我需要知道这是错误原因,而不是网络错误(例如).
Within the debug description (for example) I can see messages like "The given data was not valid JSON", but I need to know it is that rather than a network error (for example).
let decoder = JSONDecoder()
if let data = data{
do {
// process data
} catch let error {
// can access error.localizedDescription but seemingly nothing else
}
我试图转换为DecodingError
,但这似乎并没有显示更多信息.我当然不需要字符串-甚至错误代码都比这有用得多...
I tried to cast to a DecodingError
, but this does not seem to reveal more information. I certainly don't need the string - even an error code is much more helpful than this...
推荐答案
从不在解码catch
块中打印error.localizedDescription
.这将返回一个毫无意义的通用错误消息.始终打印error
实例.然后,您会得到所需的信息.
Never print error.localizedDescription
in a decoding catch
block. This returns a quite meaningless generic error message. Print always the error
instance. Then you get the desired information.
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)
}
这篇关于在Swift中使用JSONDecoder进行错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!