From 9e35cf6bd4e0fe7dd29f798957aad9a96b57ecd5 Mon Sep 17 00:00:00 2001 From: Lucas Barros Date: Sat, 21 Nov 2026 11:52:23 -0300 Subject: [PATCH] fix: keep the API error body in equinix api errors Client.Request turned any status >= 400 into an error built from the status line and never read the body, so the structured error the Equinix APIs return (error code, message, field details) never reached the user. Include the trimmed body in the error when there is one. Refs #88 Signed-off-by: Lucas Barros --- internal/api/api.go | 7 +++++++ internal/api/api_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) 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) + } +}