Skip to content
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
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))
}