Skip to content
Tutorials Center
My learning

Topics

Lesson 74 of 146 ยท Error Handling

Custom Errors

Design Swift custom errors: enums with associated values, structs, LocalizedError messages, wrapping errors into layers and catch patterns with where clauses.

In Error Handling you threw simple enum cases. Real programs need more. A failed withdrawal should say how much was needed and how much was available. A validation error should name the field. A top-level "could not load profile" error should still remember that the real cause was a network timeout. And somewhere, a human has to read a sentence that makes sense.

This lesson is about designing error types: choosing between an enum and a struct, attaching useful data, writing messages with LocalizedError, building layers of errors that wrap each other, and catching exactly the cases you care about. A good error type is part of your API: callers will switch on it, so it deserves the same care as any other type.

Enums with associated values

An enum is the default choice because the set of failures is closed and known, and the compiler can check that you handled each case. Associated values carry the details, with labels so the call sites read well:

Swift
enum BankError: Error {
    case insufficientFunds(needed: Decimal, available: Decimal)
    case accountFrozen(id: Int)
    case invalidAmount
}

Each case answers a different question for the caller. invalidAmount means "you called it wrong", accountFrozen means "try later or ask support", and insufficientFunds includes numbers the UI can show. Keep cases about what went wrong in the domain, not about which line failed.

Human-readable messages with LocalizedError

If you print or inspect an error you get the debug form, such as insufficientFunds(needed: 500, available: 100). That is fine in logs, but you cannot show it to a user. Foundation defines the protocol LocalizedError with optional properties for the human-facing parts:

Property Purpose
errorDescription A one-sentence message: what happened
failureReason Why it happened
recoverySuggestion What the user can try
helpAnchor A pointer into documentation

All have default implementations that return nil, so you only write the ones you need. Conforming also changes what error.localizedDescription returns: it becomes your errorDescription.

Swift An error type with messages for people

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first withdrawal prints 50. The second prints three lines: the message Need 500 but only 100 is available., then The balance is too low. | Deposit money first., then the raw form insufficientFunds(needed: 500, available: 100). The third prints The amount must be positive., then - | - because both optional properties are nil, then invalidAmount. The last line proves that localizedDescription works through the plain Error existential too: Account 4 is frozen.

Notice what did not change: "\(error)" still shows the enum case. LocalizedError is for people, and the default string conversion is for developers. Keep both.

The members localizedDescription and LocalizedError come from Foundation. On Linux, as in this runner, you must import Foundation to use them. Without it, print(Plain.a(2).localizedDescription) fails with error: value of type 'Plain' has no member 'localizedDescription'.

What a plain error says

If you do not conform to LocalizedError, Foundation falls back to a generic sentence. This is a classic source of unhelpful messages in apps:

Swift localizedDescription without LocalizedError

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first line is The operation could not be completed. (binary.Plain error 0.), which tells the reader nothing, and the exact wording differs between platforms. The second line, a(2), is the structured form. Rule of thumb: any error that might reach a user gets a LocalizedError conformance.

Structs and classes as errors

When the set of failures is open or the data is the same for each failure, a struct is better than an enum. Think of validation: the problem is always "a field plus a message". A struct can also conform to CustomStringConvertible to control its debug text.

Swift A struct error with a custom description

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

This prints invalid -> email: missing @ and then email. A struct error also makes it easy to add Equatable for tests: HTTPError(status: 404) == HTTPError(status: 404) is true with no extra code. Prefer value types. Classes can be errors too but are rarely a good idea, because a shared mutable object travelling through catch blocks invites surprises.

Error inherits from Sendable, so every stored property of an error should itself be safe to share across tasks. Storing a plain mutable class instance in an error produces warning: stored property 'box' of 'Sendable'-conforming struct 'BadError' has non-Sendable type 'Box'. Store strings, numbers, enums and other value types instead. See Sendable and Data Races.

Layers of errors: wrapping and hierarchies

Big programs have layers: network, storage, domain logic, user interface. Each layer should throw errors in its own vocabulary, and upper layers wrap lower ones. Swift has no class hierarchy for errors, but composition gives you the same thing:

Swift A two-level error hierarchy with where clauses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first block prints server problem 503. Study the catch clause: AppError.network(.server(let code)) where code >= 500 is a nested pattern. It matches the outer case, the inner case and binds code, then the where clause filters it. If code were 404 the clause would not match, and the next one, AppError.network(let reason), would catch it. The second block shows that one catch can list several patterns separated by commas, so .timeout and .offline share a handler and the output is retry later.

Why wrap at all? Because the upper layer should not leak lower-level types into its API. If the UI switches on AppError, you can later replace the HTTP library without changing the UI. And since .network carries the original error, logs never lose the cause.

Errors for classification, not just for messages

Sometimes callers want to ask a question about an error rather than switch on cases. Add computed properties:

Swift Useful helpers on error types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You get true, true, true, then true false. A property such as isRetryable keeps the policy in one place, so the retry loop does not need to know every status code.

Throwing initializers

Initializers can throw, which is the cleanest way to refuse to create an invalid object. If the initializer throws, no instance exists. Compare this with the optional-returning failable initializer init?: use init? when the only possible failure is "no", and init throws when the caller needs the reason.

Swift init throws

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output is true, created 3 and failed: badID(0). See Initializers for failable initializers in more depth.

Mixing error types and casting

Because Error is a protocol, a catch clause or a variable of type Error may hold any of your types, and you can test them with is and as?:

Swift Mixed errors in one array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The two lines are our error and url error, bad URL? true, and the Result prints failure(binary.Err.one). Frameworks have their own error types (URLError, DecodingError, CocoaError), and a switch like this one is how you separate yours from theirs. The Result { try ... } form at the end converts a throwing call into a value; it is the topic of The Result Type.

Design checklist

  • One concept per case. If two cases are always handled identically, merge them.
  • Carry data the caller can use (ids, limits, underlying errors), not preformatted sentences.
  • Name the type after the module or layer, like PaymentError, so autocomplete and logs make sense.
  • Make user-facing errors LocalizedError, and keep developer details in the associated values.
  • Wrap lower-level errors as you cross layers, and keep the cause.
  • Do not make everything throw. A function that cannot fail should not be throws, and "no result" is often better as nil.
  • Keep error types small and Sendable, because errors travel across tasks and actors.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why use an enum with associated values for errors?

    Enums work well when the set of failures is closed. Structs and classes can conform to Error as well.
  2. 2. What does localizedDescription return for an error that does not conform to LocalizedError?

    Foundation supplies a generic message. Conform to LocalizedError to provide a real one.
  3. 3. What does catch AppError.network(.server(let code)) where code >= 500 do?

    The pattern matches the nested cases and binds code; the where clause then filters on the bound value.
  4. 4. When is init throws better than init?

    init? can only say "no". A throwing initializer reports a specific error.
  5. 5. Which import is required on Linux to use LocalizedError and localizedDescription?

    They are defined in Foundation. Without it the compiler says the member does not exist.

Summary

  • Choose an enum for a closed set of failures and a struct when every failure has the same shape.
  • Attach data with labeled associated values, and avoid preformatted text in the cases.
  • Conform to LocalizedError (with import Foundation) to give users errorDescription, failureReason and recoverySuggestion.
  • Wrap lower-layer errors in upper-layer errors and keep the underlying cause.
  • Use nested patterns, where clauses and comma-separated patterns in catch.
  • Add computed properties such as isRetryable to keep policy next to the error.
  • Use init throws when the caller needs the reason, and init? when "no" is enough.
  • Errors are Sendable: store value types.

Next: Typed Throws