Member-only story
Error handling in Swift
How to use do-catch statements and throw custom errors to alert users (with code examples)
Error handling is a fundamental part of every app.
Not every action that users perform will succeed. Some will fail, and our app needs to tell our users, in an easy way, what just happened, and what they could try to avoid the issue.
Let me show you how we can achieve some simple error handling using throw
and do-catch
statements.

Defining & Throwing errors
To represent an error, we must use a type that conforms Error
protocol. This is an empty protocol, which means that there is no constraint to it and that we can define errors as any type that suits us best.
In general, enums
are the best way to start. Suppose that we want to handle network errors, we could define the following enum👇
enum NetworkError: Error {
case unexpected
case invalidURL(_ url: URL)
case apiError(statusCode: Int)
}
If we get an error when performing a request to our backend API, we can throw a NetworkError
.
The function that will throw the error must be marked with the
throw
keyword
enum ApiMethod {...}
struct ApiRequest…