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! 🤷🏻‍♂️

Photo by 傅甬 华 on Unsplash

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Andrew

Andrew

29 Followers

iOS Software Engineer. Punster extraordinaire. Part-time nerf herder.