The Error Protocol
The Error protocol is a label you put on your own custom type to say "this represents something going wrong."
In this page:
Defining a Custom Error Type
Conforming an enum to Error turns each of its cases into a distinct, throwable error value.
Example: Defining a Custom Error Type
enum ValidationError: Error {
case tooShort
case tooLong
}
let error = ValidationError.tooShort
print(error)
Login to try C/C++/Java/PHP code in the editor
Errors with Associated Values
Just like any other enum, an error type can carry associated values to provide more detail about what went wrong.
Example: Errors with Associated Values
enum ValidationError: Error {
case tooShort(minimum: Int)
case tooLong(maximum: Int)
}
let error = ValidationError.tooShort(minimum: 5)
print(error)
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting an error type must conform to the empty
Errorprotocol before it can be thrown withthrow. - Using a plain
Stringor generic type as an error instead of a proper enum conforming toError, losing type-safety and clarity about what can go wrong. - Defining many unrelated error cases in a single giant enum instead of separate, focused error types per domain.
Chapter Summary
- Any type can represent an error by conforming to the
Errorprotocol. - Enums are the most common way to define a set of related error cases.
Erroritself has no requirements -- it's a marker protocol.- A well-designed error type communicates exactly what can go wrong in a given operation.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: