google-api-swift-client icon indicating copy to clipboard operation
google-api-swift-client copied to clipboard

Generated Service class should handle invalid status code responses

Open omerlh opened this issue 2 years ago • 0 comments

Thanks for stopping by to let us know something could be better!

PLEASE READ: If you have a support contract with Google, please create an issue in the support console instead of filing on GitHub. This will ensure a timely response.

Is your feature request related to a problem? Please describe.

The current code does not check the status code of the response and does not pass the status code to upstream caller. So any usage of this library will not be able to determine a request has failed.

Describe the solution you'd like Ideally, raise an error in the callback if the status code is invalid. Less ideally - pass the actual response to upstream caller and let them handle status code.

Describe alternatives you've considered I've modified the local code I generated on my machine to do something like that:

func handleResponse<Z:Decodable>(
    _ data : Data?,
    _ response : URLResponse?,
    _ error : Error?,
    _ completion : @escaping(Z?, Error?) -> ()) {

        
    if let data = data {
      print(String(data:data, encoding:.utf8)!)
        if let response = response as? HTTPURLResponse {
            if (response.statusCode > 299) {
                completion(nil, HTTPError.UnexpectedStatusCode(response.statusCode, String(data:data, encoding:.utf8)!))
                return
            }
        }
      let decoder = JSONDecoder()
      do {
        let json = try? JSONSerialization.jsonObject(with: data, options: [])
        if let json = json as? [String:Any] {
          // remove the "data" wrapper that is used with some APIs (e.g. translate)
          if let payload = json["data"] {
            let payloadData = try JSONSerialization.data(withJSONObject:payload)
            completion(try decoder.decode(Z.self, from: payloadData), nil)
          } else {
            completion(try decoder.decode(Z.self, from: data), nil)
          }
        }
      } catch {
        print(String(data:data, encoding:.utf8)!)
        completion(nil, error)
      }
    } else {
      completion(nil, GoogleAPIRuntimeError.invalidResponseFromServer)
    }
  }

omerlh avatar Apr 06 '22 05:04 omerlh