Member-only story

Error handling in Swift

How to use do-catch statements and throw custom errors to alert users (with code examples)

Bruno Lorenzo
5 min readJan 9, 2024

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.

Image by Author

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

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Bruno Lorenzo
Bruno Lorenzo

Written by Bruno Lorenzo

Software Engineer | Co-creator of https://carry-on.app - A travel planner app | Former iOS Tech Lead | I write about iOS, tech, and producitivy

Responses (2)

Write a response

Hey Bruno, interesting thoughts on error handling, thank you for the good explanations.

--

It's 2024. Why not os.Logger?

--