[management/client/rest] Fix panic on unknown errors (#3865)

This commit is contained in:
M. Essam
2025-05-25 16:57:34 +02:00
committed by GitHub
parent 5bed6777d5
commit 670446d42e
2 changed files with 17 additions and 3 deletions
+9
View File
@@ -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) { func TestAccounts_Update_200(t *testing.T) {
withMockClient(func(c *rest.Client, mux *http.ServeMux) { withMockClient(func(c *rest.Client, mux *http.ServeMux) {
mux.HandleFunc("/api/accounts/Test", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/api/accounts/Test", func(w http.ResponseWriter, r *http.Request) {
+8 -3
View File
@@ -4,6 +4,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt"
"io" "io"
"net/http" "net/http"
@@ -134,7 +135,8 @@ func (c *Client) NewRequest(ctx context.Context, method, path string, body io.Re
if resp.StatusCode > 299 { if resp.StatusCode > 299 {
parsedErr, pErr := parseResponse[util.ErrorResponse](resp) parsedErr, pErr := parseResponse[util.ErrorResponse](resp)
if pErr != nil { if pErr != nil {
return nil, err
return nil, pErr
} }
return nil, errors.New(parsedErr.Message) 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) { func parseResponse[T any](resp *http.Response) (T, error) {
var ret T var ret T
if resp.Body == nil { 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) bs, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return ret, err return ret, err
} }
err = json.Unmarshal(bs, &ret) 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
} }