Skip to content

Commit

Permalink
record non-json body (#36)
Browse files Browse the repository at this point in the history
  • Loading branch information
liushuangls authored Nov 1, 2024
1 parent 36c76dc commit a12931f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
8 changes: 7 additions & 1 deletion client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)

Expand Down Expand Up @@ -59,12 +60,17 @@ func (c *Client) sendRequest(req *http.Request, v Response) error {

func (c *Client) handlerRequestError(resp *http.Response) error {
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusBadRequest {
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("error, reading response body: %w", err)
}
var errRes ErrorResponse
err := json.NewDecoder(resp.Body).Decode(&errRes)
err = json.Unmarshal(body, &errRes)
if err != nil || errRes.Error == nil {
reqErr := RequestError{
StatusCode: resp.StatusCode,
Err: err,
Body: body,
}
return &reqErr
}
Expand Down
3 changes: 2 additions & 1 deletion error.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ func (e *APIError) IsOverloadedErr() bool {
type RequestError struct {
StatusCode int
Err error
Body []byte
}

type ErrorResponse struct {
Expand All @@ -84,5 +85,5 @@ func (e *APIError) Error() string {
}

func (e *RequestError) Error() string {
return fmt.Sprintf("anthropic request error status code: %d, err: %s", e.StatusCode, e.Err)
return fmt.Sprintf("anthropic request error status code: %d, err: %s, body: %s", e.StatusCode, e.Err, e.Body)
}

0 comments on commit a12931f

Please sign in to comment.