diff --git a/internal/api/api.go b/internal/api/api.go index 65883f8..e629960 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -7,6 +7,7 @@ package api import ( + "bytes" "errors" "fmt" "io" @@ -280,6 +281,12 @@ func (c *Client) Request(apiPath, method string, data string) ([]byte, error) { }() if resp.StatusCode >= 400 { + // The error body (code, message, field details) is the useful part + // of the response, so keep it in the error. + body, _ := io.ReadAll(resp.Body) + if msg := bytes.TrimSpace(body); len(msg) > 0 { + return nil, fmt.Errorf("API error: %s: %s", resp.Status, msg) + } return nil, fmt.Errorf("API error: %s", resp.Status) } return io.ReadAll(resp.Body) diff --git a/internal/api/api_test.go b/internal/api/api_test.go index dbefb30..dec6d0f 100644 --- a/internal/api/api_test.go +++ b/internal/api/api_test.go @@ -2,6 +2,7 @@ package api import ( "net/http" + "net/http/httptest" "testing" "github.com/spf13/viper" @@ -77,3 +78,29 @@ func TestEndpointTargetsInvalid(t *testing.T) { t.Error("expected an error for an endpoint without a scheme") } } + +func TestRequestKeepsErrorBody(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/fabric/v4/ports/missing": + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`[{"errorCode":"EQ-3142102","errorMessage":"Port not found"}]` + "\n")) + default: + w.WriteHeader(http.StatusBadGateway) + } + })) + t.Cleanup(srv.Close) + c := &Client{BaseURL: srv.URL, HTTPClient: srv.Client()} + + _, err := c.Request("fabric/v4/ports/missing", http.MethodGet, "") + want := `API error: 404 Not Found: [{"errorCode":"EQ-3142102","errorMessage":"Port not found"}]` + if err == nil || err.Error() != want { + t.Errorf("error = %v, want %q", err, want) + } + + _, err = c.Request("fabric/v4/other", http.MethodGet, "") + if want := "API error: 502 Bad Gateway"; err == nil || err.Error() != want { + t.Errorf("error = %v, want %q", err, want) + } +}