Skip to content

Instantly share code, notes, and snippets.

@danielCarlosCE
Created October 13, 2017 17:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielCarlosCE/966cebd03070e0f1315dda6688d4a2ca to your computer and use it in GitHub Desktop.
Save danielCarlosCE/966cebd03070e0f1315dda6688d4a2ca to your computer and use it in GitHub Desktop.
Chain of Responsibility to handle errors on iOS application
import UIKit
class AppDelegate {
var window: UIWindow?
}
//Chain of Resposability: Handler
protocol ErrorHandler {
var errorHandlerSuccessor: ErrorHandler? {get}
func handleError(error: Error)
}
//Chain of Resposability: ConcreteHandler1
extension AppDelegate: ErrorHandler {
//this is the most generalist handler
var errorHandlerSuccessor: ErrorHandler? { return nil }
func handleError(error: Error) {
let alert = UIAlertController(title: "General Error", message: error.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)
window?.rootViewController?.present(alert, animated: true, completion: nil)
}
}
extension UIViewController: ErrorHandler {
var errorHandlerSuccessor: ErrorHandler? {
return parent ?? (UIApplication.shared.delegate as? AppDelegate)
}
func handleError(error: Error) {
//send request to successor by default
errorHandlerSuccessor?.handleError(error: error)
}
}
class LoginVC: UIViewController {
var login: (((Error?)->Void) -> Void)!
var errorLabel = UILabel()
func didClickOKButton() {
login() { error in
if let error = error {
//Chain of Resposability: Client
handleError(error: error)
return
}
}
}
}
//Chain of Resposability: ConcreteHandler2
extension LoginVC {
enum Error: Swift.Error {
case invalidCredentials
}
override func handleError(error: Swift.Error) {
guard let loginError = error as? Error else {
errorHandlerSuccessor?.handleError(error: error)
return
}
switch loginError {
case .invalidCredentials:
errorLabel.isHidden = false
errorLabel.text = "Invalid credentials."
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment