Browse Source

properly handle API errors with no response body

this is particularly important for methods like
Organizations.CheckMembership which return a 404 to indicate a
successful response of "false".
Will Norris 13 years ago
parent
commit
01e915341c
2 changed files with 28 additions and 5 deletions
  1. +4
    -5
      github.go
  2. +24
    -0
      github_test.go

+ 4
- 5
github.go View File

@ -207,12 +207,11 @@ func CheckResponse(r *http.Response) error {
}
data, err := ioutil.ReadAll(r.Body)
if err == nil {
errorResponse := new(ErrorResponse)
err = json.Unmarshal(data, errorResponse)
if err == nil && errorResponse != nil {
errorResponse.Response = r
return errorResponse
errorResponse := &ErrorResponse{Response: r}
if data != nil {
err = json.Unmarshal(data, errorResponse)
}
return errorResponse
}
return fmt.Errorf("github: got HTTP response code %d and error reading body: %v",
r.StatusCode, err)


+ 24
- 0
github_test.go View File

@ -159,6 +159,30 @@ func TestCheckResponse(t *testing.T) {
}
}
// ensure that we properly handle API errors that do not contain a response
// body
func TestCheckResponse_noBody(t *testing.T) {
res := &http.Response{
Request: &http.Request{},
StatusCode: 400,
Body: ioutil.NopCloser(strings.NewReader("")),
}
err := CheckResponse(res).(*ErrorResponse)
if err == nil {
t.Errorf("Expected error response.")
}
want := &ErrorResponse{
Response: res,
Message: "",
Errors: nil,
}
if !reflect.DeepEqual(err, want) {
t.Errorf("Error = %#v, want %#v", err, want)
}
}
func TestErrorResponse_Error(t *testing.T) {
res := &http.Response{Request: &http.Request{}}
err := ErrorResponse{Message: "m", Response: res}


Loading…
Cancel
Save