Last active
December 12, 2018 11:04
-
-
Save xxKRASHxx/9406ccf7d0fb4819896bfffa7d5bf987 to your computer and use it in GitHub Desktop.
Error handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func handle(_ errors: [Error]) -> Action { | |
func invalidToken(error: Client.Error) -> Action? { | |
guard error.message == "INVALID_TOKEN" else { return nil } | |
return InvalidateToken() | |
} | |
func paymentRequired(error: Client.Error) -> Action? { | |
guard error.message == "PAYMENT_REQUIRED" else { return nil } | |
return FailCaseCreation(context: .init(error), paymentRequired: true) | |
} | |
let handlers = [ | |
invalidToken, | |
paymentRequired | |
] | |
return errors | |
.flatMap(handlers.apply) | |
.fallback(DefaultAction()) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public extension Array { | |
public func fallback<NonOptional>(_ default: NonOptional) -> NonOptional | |
where Element == Optional<NonOptional> | |
{ | |
return self.flatten().first ?? `default` | |
} | |
public func flatten<Unwrapped>() -> [Unwrapped] | |
where Element == Optional<Unwrapped> | |
{ | |
return self.compactMap { $0 } | |
} | |
public func apply<Value, Result>(_ value: Value) -> [Result] | |
where Element == (Value) -> Result | |
{ | |
return self.map { $0(value) } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment