Simple Error-Handling when Parsing JSON with Codable in Swift: DecodingError
While working on a personal project this week, I was stumped at why the response suddenly began to fail parsing. The console had no useful information about where it was failing or why. I suspected it was the API , that the structure had changed because it’s still in beta, but it turns out, it hadn’t changed, it’s just…inconsistent. It’s in beta, so what is a boy to do! 🤷🏻♂️
As I’d made no changes to the models, parsing or networking logic, I suspected the API, but how to check without trawling through 3,000+ lines of JSON?
After a few DuckDuckGo searches, I asked the right question and found something I’d long forgot about: `DecodingError`.
Essentially, using this, I was able to catch that error, switch on it, then print out some useful information to narrow-down what models were now failing to parse
Turns out, the API hadn’t changed at all, it was just delivering an array sometimes and a String others, causing my parsing to break 🙄
I amended my model to account for the inconsistent API, and went on my way 🚀🤘🏼
📝 It’s a good idea to remove all those print statements before releasing any production builds.