diff --git a/client.go b/client.go index 2c2b0aa..c0828f0 100644 --- a/client.go +++ b/client.go @@ -102,7 +102,7 @@ func (c *Client) WithBaseURL(url string) *Client { } // Request : -func (c *Client) Request(req *http.Request, dst interface{}) error { +func (c *Client) Request(req *http.Request, dst interface{}) (err error) { c.debugf("request: %v", req) resp, err := c.httpClient.Do(req) c.debugf("response: %v", resp) @@ -110,7 +110,12 @@ func (c *Client) Request(req *http.Request, dst interface{}) error { if err != nil { return err } - defer resp.Body.Close() + defer func() { + cerr := resp.Body.Close() + if err == nil && cerr != nil { + err = cerr + } + }() switch { case 200 <= resp.StatusCode && resp.StatusCode <= 299: @@ -132,12 +137,14 @@ func (c *Client) Request(req *http.Request, dst interface{}) error { c.debugf("response body: %v", string(body)) return nil + case resp.StatusCode == http.StatusBadRequest: + return fmt.Errorf("%v: Need to send the request with GET / POST (must be capitalized)", ErrBadRequest) case resp.StatusCode == http.StatusUnauthorized: - return fmt.Errorf("%w: invalid key/secret", ErrAccessDenied) + return fmt.Errorf("%w: invalid key/secret", ErrInvalidRequest) case resp.StatusCode == http.StatusForbidden: - return fmt.Errorf("%w: not permitted", ErrAccessDenied) + return fmt.Errorf("%w: not permitted", ErrForbiddenRequest) case resp.StatusCode == http.StatusNotFound: - return ErrPathNotFound + return fmt.Errorf("%w: wrong path", ErrPathNotFound) default: return fmt.Errorf("unexpected status code %d", resp.StatusCode) } diff --git a/client_test.go b/client_test.go index 3d98006..5f52274 100644 --- a/client_test.go +++ b/client_test.go @@ -173,7 +173,7 @@ func TestClient(t *testing.T) { var got interface{} gotErr := client.Request(req, &got) - assert.ErrorIs(t, gotErr, bybit.ErrAccessDenied) + assert.ErrorIs(t, gotErr, bybit.ErrForbiddenRequest) }) t.Run("404, path not found", func(t *testing.T) { path := "/test" diff --git a/response.go b/response.go index 47fc461..9c2aad2 100644 --- a/response.go +++ b/response.go @@ -130,8 +130,22 @@ func (r *RateLimitV5Error) Error() string { } var ( - // ErrPathNotFound : Request path not found + // ErrBadRequest : + // Need to send the request with GET / POST (must be capitalized) + ErrBadRequest = errors.New("bad request") + // ErrInvalidRequest : + // 1. Need to use the correct key to access; + // 2. Need to put authentication params in the request header + ErrInvalidRequest = errors.New("authentication failed") + // ErrForbiddenRequest : + // Possible causes: + // 1. IP rate limit breached; + // 2. You send GET request with an empty json body; + // 3. You are using U.S IP + ErrForbiddenRequest = errors.New("access denied") + // ErrPathNotFound : + // Possible causes: + // 1. Wrong path; + // 2. Category value does not match account mode ErrPathNotFound = errors.New("path not found") - // ErrAccessDenied : Access denied - ErrAccessDenied = errors.New("access denied") )