diff --git a/github.go b/github.go index f731f61..52dd533 100644 --- a/github.go +++ b/github.go @@ -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) diff --git a/github_test.go b/github_test.go index 983b647..3c88f10 100644 --- a/github_test.go +++ b/github_test.go @@ -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}