Skip to content

Commit

Permalink
refactored errors (#1)
Browse files Browse the repository at this point in the history
  • Loading branch information
vtopc authored Jan 17, 2022
1 parent 308e084 commit 4a802af
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 17 deletions.
6 changes: 2 additions & 4 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,9 @@ func (c *Client) do(req *http.Request, v interface{}, expectedStatusCodes ...int
}

return &APIError{
ResponseStatusCode: resp.StatusCode,
Resp: resp,
ExpectedStatusCodes: expectedStatusCodes,
// Err is either error body or io.Copy error.
// TODO: be more specific?
Err: err,
Err: err,
}
}

Expand Down
29 changes: 17 additions & 12 deletions error.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ import (
"errors"
"fmt"
"net/http"
"net/url"
)

// ReqError request error
// ReqError request error.
type ReqError struct {
Method string
URL *url.URL
Err error // wrapped error
// Req HTTP request
Req *http.Request

// Err is either an (*APIError) or error from (*http.Client).Do()
Err error
}

// NewReqError builds ReqError
Expand All @@ -21,15 +22,14 @@ func NewReqError(req *http.Request, wrappedErr error) error {
}

return &ReqError{
Method: req.Method,
URL: req.URL,
Err: wrappedErr,
Req: req,
Err: wrappedErr,
}
}

// Error implements error interface
func (e *ReqError) Error() string {
return fmt.Sprintf("request %s %s failed: %s", e.Method, e.URL, e.Err)
return fmt.Sprintf("request %s %s failed: %s", e.Req.Method, e.Req.URL, e.Err)
}

// Unwrap provides compatibility for Go 1.13+ error chains.
Expand All @@ -39,15 +39,20 @@ func (e *ReqError) Unwrap() error {

// APIError REST API error
type APIError struct {
ResponseStatusCode int // HTTP status code
ExpectedStatusCodes []int
Err error // wrapped error

// Resp HTTP response
Resp *http.Response

// Err is either error body or error from io.Copy.
// TODO: be more specific?
Err error
}

// Error implements error interface
func (e *APIError) Error() string {
return fmt.Sprintf("wrong status code (%d not in %v): %s",
e.ResponseStatusCode, e.ExpectedStatusCodes, e.Err)
e.Resp.StatusCode, e.ExpectedStatusCodes, e.Err)
}

// Unwrap provides compatibility for Go 1.13+ error chains.
Expand Down
2 changes: 1 addition & 1 deletion error_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func TestAPIError_Error(t *testing.T) {
}{
"all_fields": {
err: &APIError{
ResponseStatusCode: 400,
Resp: &http.Response{StatusCode: 400},
ExpectedStatusCodes: []int{200},
Err: errors.New("internal fail"),
},
Expand Down

0 comments on commit 4a802af

Please sign in to comment.