Skip to content

Commit

Permalink
Refactors kube client error status handling
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexanderYastrebov committed May 5, 2022
1 parent 23211fc commit f6c9c81
Showing 1 changed file with 19 additions and 23 deletions.
42 changes: 19 additions & 23 deletions kubernetes/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,11 +115,7 @@ func (c *simpleClient) get(resource string) (io.ReadCloser, error) {
if resp.StatusCode == http.StatusForbidden {
return nil, ErrNoPermissionToAccessResource
}
b, err := io.ReadAll(resp.Body)
if err == nil {
err = fmt.Errorf("unexpected status code (%s) for GET %q: %s", http.StatusText(resp.StatusCode), resource, b)
}
return nil, err
return unexpectedStatusError(req, resp)
}

func (c *simpleClient) patch(resource string, payload []byte) (io.ReadCloser, error) {
Expand All @@ -132,17 +128,13 @@ func (c *simpleClient) patch(resource string, payload []byte) (io.ReadCloser, er
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
var err error
b, err := io.ReadAll(resp.Body)
if err == nil {
err = fmt.Errorf("unexpected status code (%s) for PATCH %q: %s", http.StatusText(resp.StatusCode), resource, b)
}

resp.Body.Close()
return io.NopCloser(bytes.NewBuffer(b)), err
if resp.StatusCode == http.StatusOK {
return resp.Body, nil
}
return resp.Body, nil
defer resp.Body.Close()

return unexpectedStatusError(req, resp)
}

func (c *simpleClient) post(resource string, payload []byte) (io.ReadCloser, error) {
Expand All @@ -155,17 +147,13 @@ func (c *simpleClient) post(resource string, payload []byte) (io.ReadCloser, err
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusCreated {
var err error
b, err := io.ReadAll(resp.Body)
if err == nil {
err = fmt.Errorf("unexpected status code (%s) for POST %q: %s", http.StatusText(resp.StatusCode), resource, b)
}

resp.Body.Close()
return io.NopCloser(bytes.NewBuffer(b)), err
if resp.StatusCode == http.StatusCreated {
return resp.Body, nil
}
return resp.Body, nil
defer resp.Body.Close()

return unexpectedStatusError(req, resp)
}

func (c *simpleClient) createRequest(method, resource string, body io.Reader) (*http.Request, error) {
Expand Down Expand Up @@ -227,3 +215,11 @@ func (a *Adapter) NewInclusterConfigClientset(ctx context.Context) error {
a.clientset, err = kubernetes.NewForConfig(cfg)
return err
}

func unexpectedStatusError(req *http.Request, resp *http.Response) (io.ReadCloser, error) {
b, err := io.ReadAll(resp.Body)
if err == nil {
err = fmt.Errorf("unexpected status code (%s) for %s %q: %s", http.StatusText(resp.StatusCode), req.Method, req.URL.Path, b)
}
return io.NopCloser(bytes.NewBuffer(b)), err
}

0 comments on commit f6c9c81

Please sign in to comment.