From 65b39c1ba92f1e078dd88c8ad94478c05f5999ab Mon Sep 17 00:00:00 2001 From: Victor Marmol Date: Tue, 16 Dec 2014 11:28:42 -0800 Subject: [PATCH] Check HTTP error code in the cAdvisor client. This will provide more meaningfull errors than the cryptic unmarshalling ones we've gotten today. Fixes #362. --- client/client.go | 3 +++ client/client_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/client/client.go b/client/client.go index a37266ac..1c57f36d 100644 --- a/client/client.go +++ b/client/client.go @@ -153,6 +153,9 @@ func (self *Client) httpGetJsonData(data, postData interface{}, url, infoName st err = fmt.Errorf("unable to read all %q: %v", infoName, err) return err } + if resp.StatusCode != 200 { + return fmt.Errorf("request failed with error: %q", strings.TrimSpace(string(body))) + } if err = json.Unmarshal(body, data); err != nil { err = fmt.Errorf("unable to unmarshal %q (Body: %q) with error: %v", infoName, string(body), err) return err diff --git a/client/client_test.go b/client/client_test.go index 67bf3c2b..5b432104 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -116,6 +116,30 @@ func TestGetContainerInfo(t *testing.T) { } } +// Test a requesy failing +func TestRequestFails(t *testing.T) { + errorText := "there was an error" + // Setup a server that simply fails. + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, errorText, 500) + })) + client, err := NewClient(ts.URL) + if err != nil { + ts.Close() + t.Fatal(err) + } + defer ts.Close() + + _, err = client.ContainerInfo("/", &info.ContainerInfoRequest{NumStats: 3}) + if err == nil { + t.Fatalf("Expected non-nil error") + } + expectedError := fmt.Sprintf("request failed with error: %q", errorText) + if err.Error() != expectedError { + t.Fatalf("Expected error %q but received %q", expectedError, err) + } +} + func TestGetSubcontainersInfo(t *testing.T) { query := &info.ContainerInfoRequest{ NumStats: 3,