Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active December 20, 2021 02:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JadenGeller/7a4ae11be08a6798002775bbd07887e3 to your computer and use it in GitHub Desktop.
Save JadenGeller/7a4ae11be08a6798002775bbd07887e3 to your computer and use it in GitHub Desktop.
Abort
struct Abort<Failure>: Error {
var failure: Failure
init(_ failureType: Failure.Type, _ failure: Failure) {
self.failure = failure
}
enum Recovery<Success> {
case success(Success)
case failure(Failure)
var success: Success {
get throws {
switch self {
case .success(let success):
return success
case .failure(let failure):
throw Abort(Failure.self, failure)
}
}
}
var failure: Failure {
get throws {
switch self {
case .success:
throw Abort<Void>()
case .failure(let failure):
return failure
}
}
}
}
static func recover<Success>(_ failureType: Failure.Type, _ body: () throws -> Success) throws -> Recovery<Success> {
do {
return .success(try body())
}
catch let error as Self {
return .failure(error.failure)
}
}
}
extension Abort where Failure == Void {
init() {
self.init(Void.self, ())
}
static func recover<Success>(_ body: () throws -> Success) throws -> Success? {
do {
return try body()
}
catch _ as Self {
return nil
}
}
static func retry<Succcess>(_ body: () throws -> Succcess) throws -> Succcess {
while true {
guard let success = try recover(body) else { continue }
return success
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment