Advertisement
Guest User

Untitled

a guest
May 24th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.83 KB | None | 0 0
  1. enum Result<T> {
  2. case isSuccess(T)
  3. // The failure error is what I want to handle. It can be a custom error if it's caught by the response parser
  4. // or any error thrown by the system
  5. case isFailure(Error)
  6. }
  7.  
  8. enum CustomError: Error {
  9.  
  10. case network(_Network)
  11. case jsonParsing(_JSONParsing)
  12.  
  13. enum _Network {
  14. case request(_Request)
  15. case response(_Response)
  16.  
  17. enum _Request {
  18. case malformedURL
  19. }
  20.  
  21. enum _Response {
  22. case status400(_Status400)
  23. case status401(_Status401)
  24.  
  25. enum _Status400 {
  26. case missingAttributeInBody
  27. case invalidAttributeValuesInBody
  28. }
  29.  
  30. enum _Status401 {
  31. case wrongCredentials
  32. }
  33. }
  34. }
  35.  
  36. enum _JSONParsing {
  37. case invalidJsonFormat
  38. }
  39. }
  40.  
  41. func checkErrorType(error: Error) {
  42. if let customError = error as? CustomError {
  43. print("Custom error")
  44. switch customError {
  45. case .network(let networkError):
  46. print("Network Error")
  47. switch networkError {
  48. case .request:
  49. print("Request Error")
  50. case .response(let responseError):
  51. print("Response Error")
  52. switch responseError {
  53. case .status400(let error400):
  54. print("Error 400")
  55. switch error400 {
  56. case .missingAttributeInBody:
  57. print("Missing attribute in body")
  58. case .invalidAttributeValuesInBody:
  59. print("Invalid attributes values in body")
  60. }
  61. case .status401(let error401):
  62. switch error401 {
  63. case .wrongCredentials:
  64. print("Wrong credentials")
  65. }
  66. }
  67. }
  68. case .jsonParsing(let jsonError):
  69. switch jsonError {
  70. case .invalidJsonFormat:
  71. print("invalid JSON format")
  72. }
  73. }
  74. } else {
  75. print("Not custom error")
  76. }
  77. }
  78.  
  79. let error1 = CustomError.network(.response(.status400(.missingAttributeInBody)))
  80. let error2 = NSError(domain: "", code: 100, userInfo: nil)
  81. let error3 = CustomError.jsonParsing(.invalidJsonFormat)
  82. let error4 = CustomError.network(.request(.malformedURL))
  83.  
  84. checkErrorType(error: error1)
  85. /* Prints:
  86. Custom error
  87. Network Error
  88. Response Error
  89. Error 400
  90. Missing attribute in body
  91. */
  92. checkErrorType(error: error2)
  93. /* Prints:
  94. Not custom error
  95. */
  96. checkErrorType(error: error3)
  97. /*
  98. Custom error
  99. invalid JSON format
  100. */
  101. checkErrorType(error: error4)
  102. /*Prints:
  103. Custom error
  104. Network Error
  105. Request Error (it stops at the request level because we haven't handled the malformedUrl specific case)
  106. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement