Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve error message #21

Merged
merged 1 commit into from
Mar 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions client/api_error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package client

type ApiError struct {
Title string
Msg string
}

func (e *ApiError) String() string {
if e.Msg == "" {
return e.Title
} else {
return e.Msg
}
}
16 changes: 13 additions & 3 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,16 @@ type UpsertResponse struct {
UpsertResult string
}

func extractApiError(resp *resty.Response) string {
var apiError ApiError
jsonError := json.Unmarshal(resp.Body(), &apiError)
if jsonError != nil {
return resp.String()
} else {
return apiError.String()
}
}

func (client *Client) Apply(resource *resource.Resource, dryMode bool) (string, error) {
url := client.baseUrl + "/" + UpperCamelToKebab(resource.Kind)
builder := client.client.R().SetBody(resource.Json)
Expand All @@ -65,7 +75,7 @@ func (client *Client) Apply(resource *resource.Resource, dryMode bool) (string,
return "", err
}
if resp.IsError() {
return "", fmt.Errorf("error applying resource %s/%s, got status code: %d:\n %s", resource.Kind, resource.Name, resp.StatusCode(), string(resp.Body()))
return "", fmt.Errorf(extractApiError(resp))
}
bodyBytes := resp.Body()
var upsertResponse UpsertResponse
Expand All @@ -90,7 +100,7 @@ func (client *Client) Get(kind string) error {
url := client.baseUrl + "/" + UpperCamelToKebab(kind)
resp, err := client.client.R().Get(url)
if resp.IsError() {
return fmt.Errorf("error listing resources of kind %s, got status code: %d:\n %s", kind, resp.StatusCode(), string(resp.Body()))
return fmt.Errorf(extractApiError(resp))
}
if err != nil {
return err
Expand All @@ -113,7 +123,7 @@ func (client *Client) Delete(kind, name string) error {
url := client.baseUrl + "/" + UpperCamelToKebab(kind) + "/" + name
resp, err := client.client.R().Delete(url)
if resp.IsError() {
return fmt.Errorf("error deleting resources %s/%s, got status code: %d:\n %s", kind, name, resp.StatusCode(), string(resp.Body()))
return fmt.Errorf(extractApiError(resp))
} else {
fmt.Printf("%s/%s deleted\n", kind, name)
}
Expand Down
Loading