Last active
June 1, 2018 09:47
-
-
Save ranmyfriend/505eddc87ddcaf49d605cb12bdc696c6 to your computer and use it in GitHub Desktop.
This MyError Helper can help us to build a concrete Errors in Swift
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
/* Error Handling in Swift*/ | |
struct MyError: Error { | |
private let possibleErrors: [Int:String] = { | |
return [ | |
200: "Success", | |
403: "Forbidden", | |
404: "Not Found", | |
500: "Internal Server Error", | |
-999: "Make use of this Error code with your own usage"] | |
}() | |
let domain: String | |
let code: Int | |
let userInfo: [String: Any]? | |
init(domain: String = "com.example", code: Int, userInfo: [String: Any]?) { | |
self.domain = domain | |
self.code = code | |
self.userInfo = userInfo | |
} | |
var localizedDescription: String { | |
if let desc = userInfo?[NSLocalizedDescriptionKey] { | |
return desc as! String | |
} | |
return possibleErrors[code] ?? "Internet Failure" | |
} | |
} | |
extension MyError { | |
static func error(with nsError: NSError) -> MyError { | |
return MyError(domain: nsError.domain, code: nsError.code, userInfo: nsError.userInfo) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment