Last active
September 1, 2018 22:53
-
-
Save joseph-elmallah/6642547cefb5dfcff47a977e1657ffed to your computer and use it in GitHub Desktop.
Basic UIResponder for iOS error propagation
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
import UIKit | |
// The status of an error handler | |
enum ErrorHandlingStatus { | |
/// The error was handled successfully and the propagation should stop | |
case handled | |
/// The error was not handled and the should be propagated further more | |
case unhandled | |
} | |
/// Conforming to this protocol allows for error handling | |
protocol ErrorHandler { | |
/// Handle an error | |
/// | |
/// - Parameter error: The error raised | |
/// - Returns: The handled status | |
func handleError(_ error: Error) -> ErrorHandlingStatus | |
} | |
// MARK: - Error Propagation | |
extension UIResponder { | |
/// Raise an error and propagate it through the error chain | |
/// | |
/// - Parameter error: The error to be raised | |
func raiseError(error: Error) { | |
// Check if the next responder can handle errors | |
guard let errorHandler = next as? ErrorHandler else { | |
// If not then carry on the raise of the error | |
next?.raiseUserError(error) | |
return | |
} | |
// If the next responder is an error handler, then ask it to handle the error and check the result | |
switch errorHandler.handleError(error) { | |
case .unhandled: | |
// If the error could not be handled, continue the propagation | |
next?.raiseUserError(error) | |
case .handled: | |
// If the error was handled, stop the propagation | |
break | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment