Member-only story
Swift Error Handling Done Right: Overcoming the Objective-C Error Legacy
Tired of cryptic Swift error messages like ‘(YourError error 0)’? Here’s how to fix them for good — with clarity and elegance.
Have you ever spent time carefully crafting error messages in your Swift app, only to find they never actually appear? Instead, your users (or you during debugging) see cryptic messages like:
“The operation couldn’t be completed. (YourApp.YourError error 0.)”
If so, you’re not alone. This confusing behavior has been tripping up Swift developers — from beginners to experts — since the language was introduced. Today, I want to explain why this happens and present a solution that makes Swift error handling more intuitive.
The Surprising Behavior of Swift’s Error Protocol
Let’s look at a simple example that demonstrates the problem:
enum NetworkError: Error {
case noConnectionToServer
case parsingFailed
var localizedDescription: String {
switch self {
case .noConnectionToServer:
return "No connection to the server."
case .parsingFailed:
return "Data parsing failed."
}
}
}
// Using the error
do {
throw…