Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing DecodingError details on decode failed in Swift

I'm starting to rewrite an application and I want to use Swift 4 Codable protocol to automatically convert json string to Objects and Structs.

Sometimes, specially at the beginning of coding, I encountered decoding problems, so I want to print these errors (whithout using always the debugger), in case some beans are not decoded correctly.

The problem is this:

enter image description here

As you can see, in the debugger, on "decodingError" object there is both:

  • the key that has got the problem (NominativoModel.denNome)
  • the error encountered (Expected to encode Array bla bla bla...).

My problem is that the only properties of that element, in the code, are errorDescription, failureReason, etc, that are ALL nil.

How can I print the values that are correctly displayed in the debugger?

like image 719
smukamuka Avatar asked Sep 27 '18 14:09

smukamuka


2 Answers

DecodingError is an enum. In your case you have to catch the typeMismatch case and print the type and the context.

catch let DecodingError.typeMismatch(type, context)  {
   print("Type '\(type)' mismatch:", context.debugDescription)
   print("codingPath:", context.codingPath)
}
like image 128
vadian Avatar answered Nov 18 '22 17:11

vadian


catch let error as DecodingError {
   switch error {
            case .typeMismatch(let key, let value):
              print("error \(key), value \(value) and ERROR: \(error.localizedDescription)")
            case .valueNotFound(let key, let value):
              print("error \(key), value \(value) and ERROR: \(error.localizedDescription)")
            case .keyNotFound(let key, let value):
              print("error \(key), value \(value) and ERROR: \(error.localizedDescription)")
            case .dataCorrupted(let key):
              print("error \(key), and ERROR: \(error.localizedDescription)")
            default:
              print("ERROR: \(error.localizedDescription)")
            }
   }
like image 44
Taras Avatar answered Nov 18 '22 17:11

Taras