Forked from nicklockwood/error-propagation.swift
Last active
April 27, 2017 14:01
Star
You must be signed in to star a gist
Typed error use-case example
This file contains 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