Skip to content

Instantly share code, notes, and snippets.

@erica
Last active November 1, 2015 04:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save erica/e4b4bd7261992a1d083c to your computer and use it in GitHub Desktop.
Save erica/e4b4bd7261992a1d083c to your computer and use it in GitHub Desktop.
public enum Error: ErrorType, CustomDebugStringConvertible {
// Add error enumerations here
case FirstError(source: String, reason: String)
public var debugDescription: String {
let mirror = Mirror(reflecting: self)
guard let item = mirror.children.first else {fatalError("Missing error enumeration item")}
guard let myEnumeration = item.label else {fatalError("Missing error enumeration label")}
let itemMirror = Mirror(reflecting:item.value)
guard let sourceItem = itemMirror.children.first else {fatalError("Missing error source child")}
guard let reasonItem = itemMirror.children.dropFirst().first else {fatalError("Missing error reason child")}
let (_, sourceStringItem) = sourceItem
let (_, reasonStringItem) = reasonItem
guard let reasonString = reasonStringItem as? String else {fatalError("Missing error reason string value")}
return "\(mirror.subjectType).\(myEnumeration): \(sourceStringItem)" + (reasonString.isEmpty ? "" : ", \"\(reasonString)\"")
}
// Call with Error.build(type:Error.FirstError)
// Or Error.build(reason:"reason text", type:Error.FirstError)
static func build(
file : String = __FILE__,
function : String = __FUNCTION__,
line : Int = __LINE__,
reason : String = "",
type errorType: (String, String) -> Error) -> Error {
return errorType("File \(file), Line \(line)", reason)
}
}
let f = Error.build(type:Error.FirstError)
let e = Error.build(reason:"Something", type:Error.FirstError)
print(f)
print(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment