Created
October 31, 2017 10:57
-
-
Save soxjke/1ed4d9c258ab66e5d0c7707f8becbbc2 to your computer and use it in GitHub Desktop.
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 Foundation | |
public struct AppError: Swift.Error { | |
public enum AppErrorReason { | |
public enum API: String { | |
case wrong_password | |
case invalid_email | |
} | |
public enum Validation: String { | |
case invalid_phone_number | |
case invalid_top_up_cost | |
} | |
public enum InternalInconsistency: String { | |
case this_shouldnt_happen_report_bug | |
} | |
case apiError(error: AppErrorReason.API) | |
case validationError(error: AppErrorReason.Validation) | |
case internalInconsistency(error: AppErrorReason.InternalInconsistency) | |
} | |
let reason: AppError.AppErrorReason | |
let userInfo: [String: Any]? | |
} | |
extension AppError { | |
var reasonCode: String { | |
switch reason { | |
case .apiError(let error): return error.rawValue | |
case .validationError(let error): return error.rawValue | |
case .internalInconsistency(let error): return error.rawValue | |
} | |
} | |
var localizedReasonCode: String { | |
return NSLocalizedString(reasonCode, comment: "Localized description for error") | |
} | |
} | |
// Usage examples | |
func validate(string: String) -> AppError? { | |
guard string.characters.count > 8 else { | |
return AppError(reason: .validationError(error: .invalid_phone_number), userInfo: nil) | |
} | |
return nil | |
} | |
func apiRequest(with completion: @escaping (Data?, AppError?) -> ()) { | |
completion(nil, AppError(reason: .apiError(error: .invalid_email), userInfo: nil)) | |
} | |
let phone = "+38097" | |
if let error = validate(string: phone) { | |
// process error | |
print(error) | |
} | |
else { | |
// validation successful | |
} | |
apiRequest { (data, error) in | |
if let error = error { | |
// process error | |
print(error) | |
} | |
else { | |
// api request successfull | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment