Ensure that we return the correct error code even if we can't read the body

This commit is contained in:
Douglas Danger Manley 2020-12-20 13:35:13 -05:00
parent 7f8d829ff7
commit 73586d4b4c

View File

@ -69,13 +69,16 @@ func (c Client) do(req *http.Request, i interface{}) error {
}
defer getResp.Body.Close()
bytes, err := ioutil.ReadAll(getResp.Body)
if err != nil {
return err
}
// Check Status Code is 1XX or 2XX
if getResp.StatusCode/100 > 2 {
bytes, err := ioutil.ReadAll(getResp.Body)
if err != nil {
// We couldn't read the output. Oh well; generate the appropriate error type anyway.
return &Meta{
Code: HTTPStatusCode(getResp.StatusCode),
}
}
resp := newJSONResponse(nil)
if err := json.Unmarshal(bytes, &resp); err != nil {
// We couldn't parse the output. Oh well; generate the appropriate error type anyway.
@ -90,6 +93,11 @@ func (c Client) do(req *http.Request, i interface{}) error {
return nil
}
bytes, err := ioutil.ReadAll(getResp.Body)
if err != nil {
return err
}
resp := newJSONResponse(i)
if err := json.Unmarshal(bytes, &resp); err != nil {
return err