From 670446d42e385397b8be87b13c5fd504c303ce86 Mon Sep 17 00:00:00 2001 From: "M. Essam" Date: Sun, 25 May 2025 17:57:34 +0300 Subject: [PATCH] [management/client/rest] Fix panic on unknown errors (#3865) --- management/client/rest/accounts_test.go | 9 +++++++++ management/client/rest/client.go | 11 ++++++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/management/client/rest/accounts_test.go b/management/client/rest/accounts_test.go index f6d48d874..d2ace4ec9 100644 --- a/management/client/rest/accounts_test.go +++ b/management/client/rest/accounts_test.go @@ -66,6 +66,15 @@ func TestAccounts_List_Err(t *testing.T) { }) } +func TestAccounts_List_ConnErr(t *testing.T) { + withMockClient(func(c *rest.Client, mux *http.ServeMux) { + ret, err := c.Accounts.List(context.Background()) + assert.Error(t, err) + assert.Contains(t, err.Error(), "404") + assert.Empty(t, ret) + }) +} + func TestAccounts_Update_200(t *testing.T) { withMockClient(func(c *rest.Client, mux *http.ServeMux) { mux.HandleFunc("/api/accounts/Test", func(w http.ResponseWriter, r *http.Request) { diff --git a/management/client/rest/client.go b/management/client/rest/client.go index 886a59f2c..25e8ad0da 100644 --- a/management/client/rest/client.go +++ b/management/client/rest/client.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "io" "net/http" @@ -134,7 +135,8 @@ func (c *Client) NewRequest(ctx context.Context, method, path string, body io.Re if resp.StatusCode > 299 { parsedErr, pErr := parseResponse[util.ErrorResponse](resp) if pErr != nil { - return nil, err + + return nil, pErr } return nil, errors.New(parsedErr.Message) } @@ -145,13 +147,16 @@ func (c *Client) NewRequest(ctx context.Context, method, path string, body io.Re func parseResponse[T any](resp *http.Response) (T, error) { var ret T if resp.Body == nil { - return ret, errors.New("No body") + return ret, fmt.Errorf("Body missing, HTTP Error code %d", resp.StatusCode) } bs, err := io.ReadAll(resp.Body) if err != nil { return ret, err } err = json.Unmarshal(bs, &ret) + if err != nil { + return ret, fmt.Errorf("Error code %d, error unmarshalling body: %w", resp.StatusCode, err) + } - return ret, err + return ret, nil }