Error handling using JSONDecoder in Swift

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

Leave a Comment