Skip to content

Instantly share code, notes, and snippets.

@xxKRASHxx
Last active December 12, 2018 11:04
Show Gist options
  • Save xxKRASHxx/9406ccf7d0fb4819896bfffa7d5bf987 to your computer and use it in GitHub Desktop.
Save xxKRASHxx/9406ccf7d0fb4819896bfffa7d5bf987 to your computer and use it in GitHub Desktop.
Error handling
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())
}
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