-
-
Save rnapier/ed1e3bb2dae8dc62f16311e2e21196f5 to your computer and use it in GitHub Desktop.
Typed error use-case example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I know you meant it to be exaggerated, but I still think this is the better approach in practice: | |
enum ClassError: Error { | |
case propertyNotFound(name: String) | |
case typeMismatch(propertyName: String) | |
} | |
class Foo { | |
var properties: [(String, Any)] = [] | |
private func validateValue(_ value: Any, for property: String) throws { // Note that I pass the name just for the error; that's ok IMO | |
// ... some logic | |
throw ClassError.typeMismatch(propertyName: property) | |
} | |
private func validateProperty(name: String, value: Any) throws { | |
if true { | |
throw ClassError.propertyNotFound(name: name) | |
} | |
try validateValue(value, for: name) // Don't need to wrap | |
} | |
func validate(name: String) throws { // should only throw a ClassError | |
for (name, value) in self.properties { | |
try validateProperty(name: name, value: value) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment