Skip to content

Instantly share code, notes, and snippets.

@swillits
Created November 14, 2015 03:44
Show Gist options
  • Save swillits/0324bbb923612f09633c to your computer and use it in GitHub Desktop.
Save swillits/0324bbb923612f09633c to your computer and use it in GitHub Desktop.
enum RandomError: ErrorType {
case UglyRandomError
}
enum TheirError: ErrorType {
case SlimeyThereError
}
enum MyError: ErrorType {
case CouldNot(TheirError)
}
func foo(i: Int) throws -> String {
// represents throwing an error I expect, and should be wrapped by MyError
guard i != 3 else {
throw TheirError.SlimeyThereError
}
// represents an error I don't expect, shouldn't be wrapped, and instead just gets thrown up past the errorWrap()
guard i != 2 else {
throw RandomError.UglyRandomError
}
return "foo(\(i))"
}
// Meh
// ------------
let s: String
do {
s = try foo(99)
} catch let err as TheirError {
throw MyError.CouldNot(err)
}
// Experiment (which I surely won't use because it's still too weird ;-)
// ------------
func errorWrap<Result, OriginalError: ErrorType, WrappingError: ErrorType>(@autoclosure closure: () throws -> Result, _ wrapError: OriginalError -> WrappingError) throws -> Result {
do {
return try closure()
} catch let x as OriginalError {
throw wrapError(x)
}
}
do {
let x:String = try errorWrap(foo(1), MyError.CouldNot)
print(x)
let y:String = try errorWrap(foo(2), MyError.CouldNot)
print(y)
let z:String = try errorWrap(foo(3), MyError.CouldNot)
print(z)
} catch let x {
print("Caught a \(x)")
}
print("Done")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment