Error handling using JSONDecoder in Swift

前端 未结 1 1545
萌比男神i
萌比男神i 2020-12-15 15:00

I am using JSONDecoder() in Swift and need to get better error messages.

Within the debug description (for example) I can see messages like \"The given

1条回答
  •  渐次进展
    2020-12-15 15:27

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

    Or for the full set of errors use

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

    0 讨论(0)
提交回复
热议问题