Skip to content

Instantly share code, notes, and snippets.

@Kametrixom
Last active June 2, 2021 14:57
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Kametrixom/21da650bd7c7006a70e3 to your computer and use it in GitHub Desktop.
protocol ContextError : ErrorType {
mutating func addContext<T>(type: T.Type)
}
protocol Contextualizable {}
extension Contextualizable {
func addContext(var error: ContextError) -> ContextError {
error.addContext(self.dynamicType)
return error
}
}
struct Error: ContextError {
var source : String
let reason : String
init(reason: String, file: String = __FILE__, function: String = __FUNCTION__, line: Int = __LINE__) {
self.reason = reason
self.source = "\(file):\(function):\(line)"
}
mutating func addContext<T>(type: T.Type) {
source += ":\(type)"
}
}
struct Parent: Contextualizable {
func myFunction() throws {
throw addContext(Error(reason: "An important reason"))
}
}
do {
try Parent().myFunction()
} catch {
print(error)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment