Skip to content

Instantly share code, notes, and snippets.

@Ravi61
Created July 13, 2017 15:30
Show Gist options
  • Save Ravi61/2d8b4fd6f5c843e9afd361d12b93c548 to your computer and use it in GitHub Desktop.
Save Ravi61/2d8b4fd6f5c843e9afd361d12b93c548 to your computer and use it in GitHub Desktop.
Decoding Error Catch
//...
do {
let model = try jsonDecoder.decode(BattleShip.self, from: jsonData!)
print(model)
} catch DecodingError.dataCorrupted(let context) {
print(context.debugDescription)
} catch DecodingError.keyNotFound(let key, let context) {
print("\(key.stringValue) was not found, \(context.debugDescription)")
} catch DecodingError.typeMismatch(let type, let context) {
print("\(type) was expected, \(context.debugDescription)")
} catch DecodingError.valueNotFound(let type, let context) {
print("no value was found for \(type), \(context.debugDescription)")
} catch {
print("I know not this error")
}
@ZUCheema
Copy link

ZUCheema commented Jun 18, 2023

Improved version to detected JSON keys order tree.

do
                {
                    let resp = try self.dateDecoder.decode(ResponseRoot<String>.self, from: success.data)
                }
                catch DecodingError.dataCorrupted(let context) {
                    print(context.debugDescription)
                } catch DecodingError.keyNotFound(let key, let context) {
                    print("API Parsing Error: (keyNotFound) \(key.stringValue) was not found, \(context.debugDescription)")
                } catch DecodingError.typeMismatch(let type, let context) {
                    print("Keys \(context.codingPath.map { key in key.stringValue }.joined(separator: "->"))")
                    print("API Parsing Error: (typeMismatch) \(type) was expected, \(context.debugDescription)")
                } catch DecodingError.valueNotFound(let type, let context) {
                    print("Keys \(context.codingPath.map { key in key.stringValue }.joined(separator: "->"))")
                    print("API Parsing Error: (valueNotFound) no value was found for \(type), \(context.debugDescription)")
                } catch {
                    print("API Parsing Error: I know not this error")
                }

This will print JOSN tree for typeMismatch and valueNotFound: rootObject -> someKey / Index X -> faulty key

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment