Skip to content

Instantly share code, notes, and snippets.

@rnapier
Forked from nicklockwood/error-propagation.swift
Last active April 27, 2017 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rnapier/ed1e3bb2dae8dc62f16311e2e21196f5 to your computer and use it in GitHub Desktop.
Save rnapier/ed1e3bb2dae8dc62f16311e2e21196f5 to your computer and use it in GitHub Desktop.
Typed error use-case example
// 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