Skip to content

Commit

Permalink
Add a way to return the body of a 5xx response.
Browse files Browse the repository at this point in the history
Fixes: prometheus#479.
Signed-off-by: Marcin Owsiany <[email protected]>
  • Loading branch information
porridge committed Oct 23, 2018
1 parent 16f375c commit 90f902c
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 9 deletions.
10 changes: 6 additions & 4 deletions api/prometheus/v1/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,9 @@ const (

// Error is an error returned by the API.
type Error struct {
Type ErrorType
Msg string
Type ErrorType
Msg string
Detail string
}

func (e *Error) Error() string {
Expand Down Expand Up @@ -470,8 +471,9 @@ func (c apiClient) Do(ctx context.Context, req *http.Request) (*http.Response, [

if code/100 != 2 && !apiError(code) {
return resp, body, &Error{
Type: ErrBadResponse,
Msg: fmt.Sprintf("bad response code %d", resp.StatusCode),
Type: ErrBadResponse,
Msg: fmt.Sprintf("bad response code %d", resp.StatusCode),
Detail: string(body),
}
}

Expand Down
44 changes: 39 additions & 5 deletions api/prometheus/v1/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,17 @@ import (
)

type apiTest struct {
do func() (interface{}, error)
inErr error
inRes interface{}
do func() (interface{}, error)
inErr error
inCode int
inRes interface{}

reqPath string
reqParam url.Values
reqMethod string
res interface{}
err error
errCheck func(error) error
}

type apiTestClient struct {
Expand Down Expand Up @@ -75,7 +77,9 @@ func (c *apiTestClient) Do(ctx context.Context, req *http.Request) (*http.Respon
}

resp := &http.Response{}
if test.inErr != nil {
if test.inCode != 0 {
resp.StatusCode = test.inCode
} else if test.inErr != nil {
resp.StatusCode = statusAPIError
} else {
resp.StatusCode = http.StatusOK
Expand Down Expand Up @@ -194,6 +198,30 @@ func TestAPIs(t *testing.T) {
},
err: fmt.Errorf("some error"),
},
{
do: doQuery("2", testTime),
inRes: "some body",
inCode: 500,
inErr: &Error{
Type: ErrBadResponse,
Msg: "bad response code: 500",
Detail: "a body",
},

reqMethod: "GET",
reqPath: "/api/v1/query",
reqParam: url.Values{
"query": []string{"2"},
"time": []string{testTime.Format(time.RFC3339Nano)},
},
errCheck: func(err error) error {
apiErr := err.(*Error)
if apiErr.Detail != "a body" {
return fmt.Errorf("%q should be %q", apiErr.Detail, "a body")
}
return nil
},
},

{
do: doQueryRange("2", Range{
Expand Down Expand Up @@ -503,7 +531,13 @@ func TestAPIs(t *testing.T) {

res, err := test.do()

if test.err != nil {
if test.errCheck != nil {
err = test.errCheck(err)
if err != nil {
t.Errorf("returned error is wrong: %s", err)
}
continue
} else if test.err != nil {
if err == nil {
t.Errorf("expected error %q but got none", test.err)
continue
Expand Down

0 comments on commit 90f902c

Please sign in to comment.