Skip to content

Instantly share code, notes, and snippets.

@alemar11
Forked from erica/context errors.swift
Created October 3, 2015 18:14
Show Gist options
  • Save alemar11/5d6739e3608028ec70d4 to your computer and use it in GitHub Desktop.
Save alemar11/5d6739e3608028ec70d4 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