小编典典

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

json

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,但这似乎并未显示更多信息。我当然不需要字符串-甚至错误代码也比这有用得多…


阅读 763

收藏
2020-07-27

共1个答案

小编典典

切勿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)
    }
2020-07-27