Skip to content

Commit

Permalink
Upon receiving unexpected status code, attempt to retrieve the body (#…
Browse files Browse the repository at this point in the history
…185)

* Upon receiving unexpected status code, attempt to retrieve the body

* Better error for when the response body cannot be read

* Add a helper to retrieve error with body
  • Loading branch information
marcinwyszynski authored Mar 10, 2022
1 parent 84368c4 commit 0ae8b18
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
15 changes: 12 additions & 3 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,6 @@ func (c *Client) authenticateRequest(req *http.Request) {
} else if c.Auth.token.Valid() {
c.Auth.token.SetAuthHeader(req)
}
return
}

func (c *Client) doRequest(req *http.Request, emptyResponse bool) (interface{}, error) {
Expand Down Expand Up @@ -356,8 +355,18 @@ func (c *Client) doRawRequest(req *http.Request, emptyResponse bool) (io.ReadClo
}

if unexpectedHttpStatusCode(resp.StatusCode) {
resp.Body.Close()
return nil, fmt.Errorf(resp.Status)
defer resp.Body.Close()

out := &UnexpectedResponseStatusError{Status: resp.Status}

body, err := io.ReadAll(resp.Body)
if err != nil {
out.Body = []byte(fmt.Sprintf("could not read the response body: %v", err))
} else {
out.Body = body
}

return nil, out
}

if emptyResponse || resp.StatusCode == http.StatusNoContent {
Expand Down
18 changes: 18 additions & 0 deletions error.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package bitbucket

import (
"errors"
"fmt"

"github.com/mitchellh/mapstructure"
)
Expand All @@ -20,3 +21,20 @@ func DecodeError(e map[string]interface{}) error {

return errors.New(bitbucketError.Message)
}

// UnexpectedResponseStatusError represents an unexpected status code
// returned from the API, along with the body, if it could be read. If the body
// could not be read, the body contains the error message trying to read it.
type UnexpectedResponseStatusError struct {
Status string
Body []byte
}

func (e *UnexpectedResponseStatusError) Error() string {
return e.Status
}

// ErrorWithBody returns an error with the given status and body.
func (e *UnexpectedResponseStatusError) ErrorWithBody() error {
return fmt.Errorf("unexpected status %s, body: %s", e.Status, string(e.Body))
}

0 comments on commit 0ae8b18

Please sign in to comment.