Skip to content

Commit bf52f94

Browse files
authored
Better error message (#4)
1 parent 852ff24 commit bf52f94

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

client_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,15 @@ func TestClientDo(t *testing.T) {
7676
wantWrappedErr: errors.New("wrong status code (500 not in [200]): {\"error\":\"some error\"}"),
7777
},
7878

79+
"negative_wrong_status_codes": {
80+
method: http.MethodGet,
81+
urlPostfix: "/health",
82+
statusCode: http.StatusInternalServerError,
83+
expectedStatusCodes: []int{http.StatusOK, http.StatusAccepted},
84+
respBody: []byte(`{"error":"some error"}`),
85+
wantWrappedErr: errors.New("wrong status code (500 not in [200, 202]): {\"error\":\"some error\"}"),
86+
},
87+
7988
"negative_not_a_pointer": {
8089
method: http.MethodGet,
8190
urlPostfix: "/health",

error.go

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import (
44
"errors"
55
"fmt"
66
"net/http"
7+
"strconv"
8+
"strings"
79
)
810

911
// ReqError request error.
@@ -51,8 +53,13 @@ type APIError struct {
5153

5254
// Error implements error interface
5355
func (e *APIError) Error() string {
54-
return fmt.Sprintf("wrong status code (%d not in %v): %s",
55-
e.Resp.StatusCode, e.ExpectedStatusCodes, e.Err)
56+
codes := make([]string, 0, len(e.ExpectedStatusCodes))
57+
for _, code := range e.ExpectedStatusCodes {
58+
codes = append(codes, strconv.Itoa(code))
59+
}
60+
61+
return fmt.Sprintf("wrong status code (%d not in [%s]): %s",
62+
e.Resp.StatusCode, strings.Join(codes, ", "), e.Err)
5663
}
5764

5865
// Unwrap provides compatibility for Go 1.13+ error chains.

0 commit comments

Comments
 (0)