Skip to content

Commit ccf2a4d

Browse files
authored
Add api err type (#24)
* Add api err type * Shush linter
1 parent 6d6a3b0 commit ccf2a4d

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

client.go

+14-1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,15 @@ type Castle struct {
2121
apiSecret string
2222
}
2323

24+
type APIError struct {
25+
StatusCode int `json:"status_code"`
26+
Message string `json:"message"`
27+
}
28+
29+
func (e *APIError) Error() string {
30+
return fmt.Sprintf("status code: %d, message: %s", e.StatusCode, e.Message)
31+
}
32+
2433
// New creates a new castle client with default http client
2534
func New(secret string) (*Castle, error) {
2635
return NewWithHTTPClient(secret, http.DefaultClient)
@@ -95,7 +104,11 @@ func (c *Castle) sendCall(ctx context.Context, r *castleAPIRequest, url string)
95104
defer res.Body.Close() // nolint: gosec
96105
if res.StatusCode != http.StatusCreated {
97106
b, _ := io.ReadAll(res.Body) // nolint: errcheck
98-
return RecommendedActionNone, fmt.Errorf("expected 201 status but got %d: %s", res.StatusCode, string(b))
107+
108+
return RecommendedActionNone, &APIError{
109+
StatusCode: res.StatusCode,
110+
Message: string(b),
111+
}
99112
}
100113

101114
resp := &castleAPIResponse{}

client_test.go

+6
Original file line numberDiff line numberDiff line change
@@ -63,12 +63,15 @@ func TestCastle_SendFilterCall(t *testing.T) {
6363
fs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
6464
w.Header().Set("content-type", "application/json")
6565
w.WriteHeader(400)
66+
w.Write([]byte(`foo`)) // nolint: errcheck
6667
}))
6768

6869
castle.FilterEndpoint = fs.URL
6970

7071
res, err := cstl.Filter(ctx, req)
7172
assert.Error(t, err)
73+
assert.IsType(t, &castle.APIError{}, err)
74+
assert.Equal(t, &castle.APIError{StatusCode: 400, Message: "foo"}, err)
7275
assert.Equal(t, castle.RecommendedActionNone, res)
7376
})
7477

@@ -303,13 +306,16 @@ func TestCastle_SendRiskCall(t *testing.T) {
303306
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
304307
w.Header().Set("content-type", "application/json")
305308
w.WriteHeader(400)
309+
w.Write([]byte(`foo`)) // nolint: errcheck
306310
}))
307311
t.Cleanup(ts.Close)
308312

309313
castle.RiskEndpoint = ts.URL
310314

311315
res, err := cstl.Risk(ctx, req)
312316
assert.Error(t, err)
317+
assert.IsType(t, &castle.APIError{}, err)
318+
assert.Equal(t, &castle.APIError{StatusCode: 400, Message: "foo"}, err)
313319
assert.Equal(t, castle.RecommendedActionNone, res)
314320
})
315321

0 commit comments

Comments
 (0)