簡體   English   中英

Alamofire responseDecodable for model 用於響應和錯誤

[英]Alamofire responseDecodable for model for response and error

我正在使用 Alamofire 從移動應用撥打 API 電話。 我的結構是 map 來自 Alamofire API 以這種方式調用

APIManager.shared.session.request(UserRouter.signUp(username, password)).responseDecodable (of: User.self) { response in
  complition(response.value, response.error)
}

當 API 調用失敗並返回 API 錯誤是 JSON 格式我得到AFError

▿ Optional<AFError>
  ▿ some : AFError
    ▿ responseSerializationFailed : 1 element
      ▿ reason : ResponseSerializationFailureReason
        ▿ decodingFailed : 1 element
          ▿ error : DecodingError
            ▿ keyNotFound : 2 elements
              - .0 : ContainerKeys(stringValue: "user", intValue: nil)
              ▿ .1 : Context
                - codingPath : 0 elements
                - debugDescription : "Cannot get KeyedDecodingContainer<CodingKeys> -- no value found for key ContainerKeys(stringValue: \"user\", intValue: nil) (\"user\")"
                - underlyingError : nil

這是 API 返回的那個電話

{
  "success": false,
  "errors": [
    "Email can't be blank",
    "Password can't be blank"
  ]
}

我最終寫了這個來處理它:

struct APIError: Error, Decodable {
    var success: Bool
    var errors: [String]
}
    APIManager.shared.session.request(UserRouter.signUp(username, password)).responseDecodable (of: User.self) { response in
        switch response.result {
        case .success(let value):
            complition(value, nil)
        case .failure:
            let somethingWrong = APIError(success: false, errors: ["Something went wrong. Please try again."])

            guard let data = response.data else {
                complition(nil, somethingWrong)
                return
            }
            
            do {
                let error = try JSONDecoder().decode(APIError.self, from: data)
                complition(nil, error)
            } catch {
                complition(nil, somethingWrong)
            }

        }
    }

如何更好地編寫這段代碼,也許 Alamofire 也支持 map 錯誤 model。

這里的典型解決方案是使用枚舉作為基本響應類型。

enum APIResult<Success: Decodable> {
  case success(Success)
  case failure(APIError)
}

然后,您可以使枚舉直接符合Decodable (為此有很多解決方案),或者創建您自己的 Alamofire ResponseSerializer來為您處理解碼邏輯。 這種方法工作量更大,但更靈活,因為您可以在解析時考慮請求和響應。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM