Skip to content

Commit

Permalink
Better error message (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
vtopc authored Aug 1, 2023
1 parent 852ff24 commit bf52f94
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
9 changes: 9 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,15 @@ func TestClientDo(t *testing.T) {
wantWrappedErr: errors.New("wrong status code (500 not in [200]): {\"error\":\"some error\"}"),
},

"negative_wrong_status_codes": {
method: http.MethodGet,
urlPostfix: "/health",
statusCode: http.StatusInternalServerError,
expectedStatusCodes: []int{http.StatusOK, http.StatusAccepted},
respBody: []byte(`{"error":"some error"}`),
wantWrappedErr: errors.New("wrong status code (500 not in [200, 202]): {\"error\":\"some error\"}"),
},

"negative_not_a_pointer": {
method: http.MethodGet,
urlPostfix: "/health",
Expand Down
11 changes: 9 additions & 2 deletions error.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"errors"
"fmt"
"net/http"
"strconv"
"strings"
)

// ReqError request error.
Expand Down Expand Up @@ -51,8 +53,13 @@ type APIError struct {

// Error implements error interface
func (e *APIError) Error() string {
return fmt.Sprintf("wrong status code (%d not in %v): %s",
e.Resp.StatusCode, e.ExpectedStatusCodes, e.Err)
codes := make([]string, 0, len(e.ExpectedStatusCodes))
for _, code := range e.ExpectedStatusCodes {
codes = append(codes, strconv.Itoa(code))
}

return fmt.Sprintf("wrong status code (%d not in [%s]): %s",
e.Resp.StatusCode, strings.Join(codes, ", "), e.Err)
}

// Unwrap provides compatibility for Go 1.13+ error chains.
Expand Down

0 comments on commit bf52f94

Please sign in to comment.