You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+56-41Lines changed: 56 additions & 41 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,18 +1,21 @@
1
1
# ErrorKit
2
2
3
-
**ErrorKit** makes error handling in Swift more intuitive. It reduces boilerplate code while providing clearer insights. Helpful for users, fun for developers!
3
+
ErrorKit makes error handling in Swift more intuitive. It reduces boilerplate code while providing clearer insights into errors - helpful for users, fun for developers!
4
4
5
-
*TODO: Add a list of advantages of using ErrorKit over Swift’s native error handling types.*
5
+
## Table of Contents
6
+
-[The Problem with Swift's Error Protocol](#the-problem-with-swifts-error-protocol)
-[Typed Throws for System Functions](#typed-throws-for-system-functions)
11
+
-[Error Nesting with Catching](#error-nesting-with-catching)
12
+
-[Error Chain Debugging](#error-chain-debugging)
6
13
7
-
---
14
+
## The Problem with Swift's Error Protocol
8
15
9
-
## Why We Introduced the `Throwable` Protocol to Replace `Error`
16
+
Swift's `Error` protocol is simple – too simple. While it has no requirements, it provides a computed property `localizedDescription` that's commonly used for logging errors and displaying messages to users. However, this simplicity leads to unexpected behavior and confusion.
10
17
11
-
### The Confusing `Error` API
12
-
13
-
Swift's `Error` protocol is simple – too simple. It has no requirements, but it offers one computed property, `localizedDescription`, which is often used to log errors or display messages to users.
14
-
15
-
Consider the following example where we provide a `localizedDescription` for an enum:
18
+
Consider this example of providing a `localizedDescription` for an error enum:
You might expect this to work seamlessly, but it doesn’t. If we randomly throw an error and print its `localizedDescription`, like in the following SwiftUI view:
34
+
You might expect this to work seamlessly, but trying it out reveals a surprise: 😱
32
35
33
36
```swift
34
37
structContentView: View {
@@ -44,40 +47,47 @@ struct ContentView: View {
44
47
}
45
48
```
46
49
47
-
The console output will surprise you: 😱
50
+
The console output is not what you'd expect:
48
51
49
52
```bash
50
-
Caught error with message: The operation couldn’t be completed. (ErrorKitDemo.NetworkError error 0.)
53
+
Caught error with message: The operation couldn't be completed. (ErrorKitDemo.NetworkError error 0.)
51
54
```
52
55
53
-
There’s no information about the specific error case. Not even the enum case name appears, let alone the custom message! Why? Because Swift’s `Error` protocol is bridged to `NSError`, which uses `domain`, `code`, and `userInfo` instead.
56
+
There's no information about the specific error case - not even the enum case name appears, let alone your custom message!This happens because Swift's `Error` protocol is bridged to `NSError`, which uses a different system of `domain`, `code`, and `userInfo`.
54
57
55
58
### The "Correct" Way: `LocalizedError`
56
59
57
-
The correct approach is to conform to `LocalizedError`, which defines the following optional properties:
58
-
60
+
Swift provides `LocalizedError` as the "proper" solution, with these optional properties:
59
61
- `errorDescription: String?`
60
62
- `failureReason: String?`
61
63
- `recoverySuggestion: String?`
62
64
- `helpAnchor: String?`
63
65
64
-
However, since all of these properties are optional, you won’t get any compiler errors if you forget to implement them. Worse, only `errorDescription` affects `localizedDescription`. Fields like `failureReason` and `recoverySuggestion` are ignored, while `helpAnchor` is rarely used nowadays.
66
+
However, this approach has serious issues:
67
+
- All properties are optional - no compiler enforcement
68
+
- Only `errorDescription` affects `localizedDescription`
69
+
- `failureReason` and `recoverySuggestion` are often ignored
70
+
- `helpAnchor` is rarely used in modern development
65
71
66
72
This makes `LocalizedError` both confusing and error-prone.
67
73
68
-
###The Solution: `Throwable`
74
+
## The Throwable Protocol Solution
69
75
70
-
To address these issues, **ErrorKit** introduces the `Throwable` protocol:
76
+
ErrorKit introduces the `Throwable` protocol to solve these issues:
71
77
72
78
```swift
73
79
public protocol Throwable: LocalizedError {
74
80
var userFriendlyMessage: String { get }
75
81
}
76
82
```
77
83
78
-
This protocol is simple and clear. It’s named `Throwable` to align with Swift’s `throw` keyword and follows Swift’s convention of using the `able` suffix (like `Codable` and `Identifiable`). Most importantly, it requires the `userFriendlyMessage` property, ensuring your errors behave exactly as expected.
84
+
This protocol is simple and clear:
85
+
- Named to align with Swift's `throw` keyword
86
+
- Follows Swift's naming convention (`able` suffix like `Codable`)
87
+
- Requires single, non-optional `userFriendlyMessage` property
case .noConnectionToServer:"Unable to connect to the server."
90
-
case .parsingFailed:"Data parsing failed."
99
+
case .noConnectionToServer: String(localized: "Unable to connect to the server.")
100
+
case .parsingFailed: String(localized: "Data parsing failed.")
91
101
}
92
102
}
93
103
}
94
104
```
95
105
96
106
When you print `error.localizedDescription`, you'll get exactly the message you expect! 🥳
97
107
98
-
### Even Shorter Error Definitions
108
+
### Quick Start During Development
99
109
100
-
Not all apps are localized, and developers may not have time to provide localized descriptions immediately. To make error handling even simpler, `Throwable` allows you to define your error messages using raw values:
110
+
During early development phases when you're rapidly prototyping, `Throwable` allows you to define error messages using raw valuesfor maximum speed:
This approach eliminates boilerplate code while keeping the error definitions concise and descriptive.
119
+
This approach eliminates boilerplate code while keeping error definitions concise and descriptive. However, remember to transition to proper localization using `String(localized:)` before shipping your app.
110
120
111
121
### Summary
112
122
113
123
> Conform your custom error types to `Throwable` instead of `Error` or `LocalizedError`. The `Throwable` protocol requires only `userFriendlyMessage: String`, ensuring your error messages are exactly what you expect – no surprises.
114
124
115
-
116
125
## Enhanced Error Descriptions with `userFriendlyMessage(for:)`
117
126
118
-
ErrorKit goes beyond simplifying error handling — it enhances the clarity of error messages by providing improved, localized descriptions. With the `ErrorKit.userFriendlyMessage(for:)` function, developers can deliver clear, user-friendly error messages tailored to their audience.
127
+
ErrorKit enhances error clarity through the `ErrorKit.userFriendlyMessage(for:)` function, designed to provide improved error descriptions for any error type.
119
128
120
129
### How It Works
121
130
122
-
The `userFriendlyMessage(for:)` function analyzes the provided `Error` and returns an enhanced, localized message. It draws on a community-maintained collection of descriptions to ensure the messages are accurate, helpful, and continuously evolving.
131
+
The `userFriendlyMessage(for:)`functionanalyzes the provided `Error` and returns an enhancedmessage that's clear and helpful. It leverages a community-maintained collection of descriptions to ensure messages are accurateand continuously improving.
123
132
124
133
### Supported Error Domains
125
134
126
-
ErrorKit supports errors from various domains such as `Foundation`, `CoreData`, `MapKit`, and more. These domains are continuously updated, providing coverage for the most common error types in Swift development.
135
+
ErrorKit provides enhanced messages for errors from various domains:
136
+
- Foundation
137
+
- CoreData
138
+
- MapKit
139
+
- And many more...
140
+
141
+
These domains are continuously updated to provide coverage for the most common error types in Swift development.
127
142
128
143
### Usage Example
129
144
130
-
Here’s how to use `userFriendlyMessage(for:)` to handle errors gracefully:
145
+
Here's how to use `userFriendlyMessage(for:)` to handle errors gracefully:
131
146
132
147
```swift
133
148
do {
@@ -143,20 +158,23 @@ do {
143
158
144
159
### Why Use `userFriendlyMessage(for:)`?
145
160
146
-
-**Localization**: Error messages are localized to ~40 languages to provide a better user experience.
-**Community Contributions**: The descriptions are regularly improved by the developer community. If you encounter a new or unexpected error, feel free to contribute by submitting a pull request.
- **Consistency**: Provides standardized error messaging across your application
163
+
- **Community-Driven**: Messages are regularly improved through developer contributions
164
+
- **Comprehensive**: Covers a wide range of common Swift error scenarios
149
165
150
166
### Contribution Welcome!
151
167
152
-
Found a bug or missing description? We welcome your contributions! Submit a pull request (PR), and we’ll gladly review and merge it to enhance the library further.
168
+
Found a bug or missing description? We welcome your contributions! Submit a pull request (PR), and we'll gladly review and merge it to enhance the library further.
153
169
154
-
> **Note:** The enhanced error descriptions are constantly evolving, and we’re committed to making them as accurate and helpful as possible.
170
+
> **Note:** The enhanced error descriptions are constantly evolving, and we're committed to making them as accurate and helpful as possible.
155
171
156
172
## Overloads of Common System Functions with Typed Throws
157
173
158
174
ErrorKit introduces typed-throws overloads for common system APIs like `FileManager` and `URLSession`, providing more granular error handling and improved code clarity. These overloads allow you to handle specific error scenarios with tailored responses, making your code more robust and easier to maintain.
159
175
176
+
### Discovery and Usage
177
+
160
178
To streamline discovery, ErrorKit uses the same API names prefixed with `throwable`. These functions throw specific errors that conform to `Throwable`, allowing for clear and informative error messages.
161
179
162
180
**Enhanced User-Friendly Error Messages:**
@@ -171,7 +189,7 @@ do {
171
189
} catch {
172
190
switch error {
173
191
case FileManagerError.noWritePermission:
174
-
// Request write permission from the user intead of showing error message
192
+
// Request write permission from the user instead of showing error message
175
193
default:
176
194
// Common error cases have a more descriptive message
177
195
showErrorDialog(error.localizedDescription)
@@ -210,7 +228,6 @@ Here, the code leverages the specific error types to implement various kinds of
210
228
211
229
By utilizing these typed-throws overloads, you can write more robust and maintainable code. ErrorKit's enhanced user-friendly messages and ability to handle specific errors with code lead to a better developer and user experience. As the library continues to evolve, we encourage the community to contribute additional overloads and error types for common system APIs to further enhance its capabilities.
212
230
213
-
214
231
## Built-in Error Types for Common Scenarios
215
232
216
233
ErrorKit provides a set of pre-defined error types for common scenarios that developers encounter frequently. These built-in types conform to `Throwable` and can be used with both typed throws (`throws(DatabaseError)`) and classical throws declarations.
@@ -294,7 +311,6 @@ When contributing:
294
311
295
312
Together, we can build a comprehensive set of error types that cover most common scenarios in Swift development and create a more unified error handling experience across the ecosystem.
296
313
297
-
298
314
## Simplified Error Nesting with the `Catching` Protocol
299
315
300
316
ErrorKit's `Catching` protocol simplifies error handling in modular applications by providing an elegant way to handle nested error hierarchies. It eliminates the need for explicit wrapper cases while maintaining type safety through typed throws.
@@ -319,8 +335,6 @@ enum ProfileError: Error {
319
335
}
320
336
```
321
337
322
-
This leads to verbose error types and tedious error handling code when attempting to use typed throws.
323
-
324
338
### The Solution: `Catching` Protocol
325
339
326
340
ErrorKit's `Catching` protocol provides a single `caught`case that can wrap any error, plus a convenient `catch`functionfor automatic error wrapping:
@@ -329,6 +343,8 @@ ErrorKit's `Catching` protocol provides a single `caught` case that can wrap any
329
343
enum ProfileError: Throwable, Catching {
330
344
case validationFailed(field: String)
331
345
case caught(Error) // Single case handles all nested errors!
The `Catching` protocol makes error handling in Swift more intuitive and maintainable, especially in larger applications with complex error hierarchies. Combined with typed throws, it provides a powerful way to handle errors while keeping your code clean and maintainable.
424
440
425
-
426
441
## Enhanced Error Debugging with Error Chain Description
427
442
428
443
One of the most challenging aspects of error handling in Swift is tracing where exactly an error originated, especially when using error wrapping across multiple layers of an application. ErrorKit solves this with powerful debugging tools that help you understand the complete error chain.
0 commit comments