Skip to content

Instantly share code, notes, and snippets.

@zyg-github
Forked from erica/context errors.swift
Created December 28, 2015 06:27
Show Gist options
  • Save zyg-github/13a9f8efe2b2ec67a69f to your computer and use it in GitHub Desktop.
Save zyg-github/13a9f8efe2b2ec67a69f to your computer and use it in GitHub Desktop.
public struct Error: ErrorType {
let source: String; let reason: String
public init(_ source: String = __FILE__, _ reason: String) {
self.reason = reason; self.source = source
}
}
protocol Contextualizable {}
extension Contextualizable {
func functionContext(function : String = __FUNCTION__) -> String {
return "\(self.dynamicType):\(function)"
}
func fileContext(file : String = __FILE__, line : Int = __LINE__) -> String {
return "\(file):\(line)"
}
func currentContext(file : String = __FILE__, function : String = __FUNCTION__, line : Int = __LINE__) -> String {
return "\(self.dynamicType):\(function):\(file):\(line)"
}
func contextString(items: Any..., file : String = __FILE__, function : String = __FUNCTION__, line : Int = __LINE__) -> String {
return "\(function):\(self.dynamicType):\(file):\(line) " + items.map({"\($0)"}).joinWithSeparator(", ")
}
func contextPrint(items: Any..., file : String = __FILE__, function : String = __FUNCTION__, line : Int = __LINE__) {
print("\(function):\(self.dynamicType):\(file):\(line) " + items.map({"\($0)"}).joinWithSeparator(", "))
}
func contextError(items: Any..., file : String = __FILE__, function : String = __FUNCTION__, line : Int = __LINE__) -> Error {
return Error("\(function):\(self.dynamicType):\(file):\(line) ", items.map({"\($0)"}).joinWithSeparator(", "))
}
}
public struct Parent: Contextualizable {
func myFunction() throws {
throw contextError("Some good reason", 2, 3)
}
}
func dotry(block: () throws -> Void) {
do {try block()} catch {print(error)}
}
dotry {try Parent().myFunction()}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment