Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Decode JSON body when Prometheus returns 400 to an api call #414

Merged
merged 2 commits into from
Jun 4, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions api/prometheus/v1/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,11 @@ type apiResponse struct {
Error string `json:"error"`
}

func apiError(code int) bool {
// These are the codes that Prometheus sends when it returns an error.
return code == statusAPIError || code == http.StatusBadRequest
}

func (c apiClient) Do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) {
resp, body, err := c.Client.Do(ctx, req)
if err != nil {
Expand All @@ -463,7 +468,7 @@ func (c apiClient) Do(ctx context.Context, req *http.Request) (*http.Response, [

code := resp.StatusCode

if code/100 != 2 && code != statusAPIError {
if code/100 != 2 && !apiError(code) {
return resp, body, &Error{
Type: ErrBadResponse,
Msg: fmt.Sprintf("bad response code %d", resp.StatusCode),
Expand All @@ -479,14 +484,14 @@ func (c apiClient) Do(ctx context.Context, req *http.Request) (*http.Response, [
}
}

if (code == statusAPIError) != (result.Status == "error") {
if apiError(code) != (result.Status == "error") {
err = &Error{
Type: ErrBadResponse,
Msg: "inconsistent body for response code",
}
}

if code == statusAPIError && result.Status == "error" {
if apiError(code) && result.Status == "error" {
err = &Error{
Type: result.ErrorType,
Msg: result.Error,
Expand Down
15 changes: 14 additions & 1 deletion api/prometheus/v1/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -606,7 +606,20 @@ func TestAPIClientDo(t *testing.T) {
response: "bad json",
err: &Error{
Type: ErrBadResponse,
Msg: "bad response code 400",
Msg: "bad response code 500",
},
code: http.StatusInternalServerError,
},
{
response: &apiResponse{
Status: "error",
Data: json.RawMessage(`null`),
ErrorType: ErrBadData,
Error: "end timestamp must not be before start time",
},
err: &Error{
Type: ErrBadData,
Msg: "end timestamp must not be before start time",
},
code: http.StatusBadRequest,
},
Expand Down