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.

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Flutter (Eventually) at the Speed of Thought

The First Week of General Assembly DSI and Some Basic Python

Top Data Centre and Cloud Hosting Company: HTS Hosting

Serverless Media Function on Amazon EKS

How to download udemy courses on your computer

Hitting the ground running as a QA Engineer in a new role

literally just spent almost two hours clicking

Why Do We Need JPEG Compression and How It’s Technically Working?

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

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

More from Medium

Hashable in Swift

Copiable in Swift — Clean Approach

Abstract vector created by vectorjuice — www.freepik.com

iOS CI&CD tips pt 1

How to test push notifications on iOS simulator