Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- enum Result<T> {
- case isSuccess(T)
- // The failure error is what I want to handle. It can be a custom error if it's caught by the response parser
- // or any error thrown by the system
- case isFailure(Error)
- }
- enum CustomError: Error {
- case network(_Network)
- case jsonParsing(_JSONParsing)
- enum _Network {
- case request(_Request)
- case response(_Response)
- enum _Request {
- case malformedURL
- }
- enum _Response {
- case status400(_Status400)
- case status401(_Status401)
- enum _Status400 {
- case missingAttributeInBody
- case invalidAttributeValuesInBody
- }
- enum _Status401 {
- case wrongCredentials
- }
- }
- }
- enum _JSONParsing {
- case invalidJsonFormat
- }
- }
- func checkErrorType(error: Error) {
- if let customError = error as? CustomError {
- print("Custom error")
- switch customError {
- case .network(let networkError):
- print("Network Error")
- switch networkError {
- case .request:
- print("Request Error")
- case .response(let responseError):
- print("Response Error")
- switch responseError {
- case .status400(let error400):
- print("Error 400")
- switch error400 {
- case .missingAttributeInBody:
- print("Missing attribute in body")
- case .invalidAttributeValuesInBody:
- print("Invalid attributes values in body")
- }
- case .status401(let error401):
- switch error401 {
- case .wrongCredentials:
- print("Wrong credentials")
- }
- }
- }
- case .jsonParsing(let jsonError):
- switch jsonError {
- case .invalidJsonFormat:
- print("invalid JSON format")
- }
- }
- } else {
- print("Not custom error")
- }
- }
- let error1 = CustomError.network(.response(.status400(.missingAttributeInBody)))
- let error2 = NSError(domain: "", code: 100, userInfo: nil)
- let error3 = CustomError.jsonParsing(.invalidJsonFormat)
- let error4 = CustomError.network(.request(.malformedURL))
- checkErrorType(error: error1)
- /* Prints:
- Custom error
- Network Error
- Response Error
- Error 400
- Missing attribute in body
- */
- checkErrorType(error: error2)
- /* Prints:
- Not custom error
- */
- checkErrorType(error: error3)
- /*
- Custom error
- invalid JSON format
- */
- checkErrorType(error: error4)
- /*Prints:
- Custom error
- Network Error
- Request Error (it stops at the request level because we haven't handled the malformedUrl specific case)
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement