OOResult.swift 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. //
  2. // OOResult.swift
  3. // o2app
  4. //
  5. // Created by 刘振兴 on 2017/8/24.
  6. // Copyright © 2017年 zone. All rights reserved.
  7. //
  8. import Foundation
  9. import HandyJSON
  10. import Moya
  11. public final class OOResult<T:BaseModel> {
  12. var model:T?
  13. var error:OOAppError?
  14. fileprivate var sourceError:Swift.Error?
  15. init(_ result:Result<Response,MoyaError>) {
  16. switch result {
  17. case .success(let resp):
  18. self.model = resp.mapObject(T.self)
  19. if let _ = model {
  20. if model?.isSuccess() == false {
  21. self.error = OOAppError.common(type: "APPError", message: model?.message ?? "", statusCode: 10001)
  22. }
  23. }else{
  24. self.error = OOAppError.common(type: "systemError", message: "转换出错", statusCode: 10001)
  25. }
  26. break
  27. case .failure(let err):
  28. self.sourceError = err
  29. transError()
  30. break
  31. }
  32. }
  33. func isResultSuccess() -> Bool {
  34. guard let _ = error else {
  35. return true
  36. }
  37. return false
  38. }
  39. fileprivate func transError() {
  40. guard let err = self.sourceError else {
  41. return
  42. }
  43. if err is MoyaError {
  44. let mErr = err as! MoyaError
  45. switch mErr {
  46. case .imageMapping(let resp):
  47. self.error = OOAppError.imageMapping(message: mErr.errorDescription!, statusCode: (mErr.response?.statusCode)!, data: resp.data)
  48. break
  49. case .jsonMapping(let resp):
  50. self.error = OOAppError.jsonMapping(message: mErr.errorDescription!, statusCode: (mErr.response?.statusCode)!, data: resp.data)
  51. break
  52. case .requestMapping(let str):
  53. self.error = OOAppError.requestMapping(str)
  54. break
  55. case .statusCode(let resp):
  56. self.error = OOAppError.statusCode(message: mErr.errorDescription!, statusCode: (mErr.response?.statusCode)!, data: resp.data)
  57. break
  58. case .stringMapping(let resp):
  59. self.error = OOAppError.stringMapping(message: mErr.errorDescription!, statusCode: (mErr.response?.statusCode)!, data: resp.data)
  60. break
  61. case .underlying(let uErr):
  62. self.error = OOAppError.underlying(uErr.0 as! Error)
  63. break
  64. case .objectMapping(let err,let resp):
  65. self.error = OOAppError.objectMapping(err, resp)
  66. break
  67. case .encodableMapping(let err):
  68. self.error = OOAppError.encodableMapping(err)
  69. break
  70. case .parameterEncoding(let err):
  71. self.error = OOAppError.parameterEncoding(err)
  72. break
  73. }
  74. }
  75. }
  76. }