Skip to content

Commit

Permalink
Ensure response middleware executed when error occurs
Browse files Browse the repository at this point in the history
  • Loading branch information
imroc committed Jan 11, 2023
1 parent 3b87ac1 commit 28436eb
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 13 deletions.
10 changes: 3 additions & 7 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -1319,17 +1319,13 @@ func (c *Client) roundTrip(r *Request) (resp *Response, err error) {
httpResponse, err = c.httpClient.Do(r.RawRequest)
resp.Response = httpResponse

if err != nil {
return
}
// auto-read response body if possible
if !c.disableAutoReadResponse && !r.isSaveResponse && !r.disableAutoReadResponse {
if err == nil && !c.disableAutoReadResponse && !r.isSaveResponse && !r.disableAutoReadResponse {
_, err = resp.ToBytes()
if err != nil {
return
}
// restore body for re-reads
resp.Body = ioutil.NopCloser(bytes.NewReader(resp.body))
} else if err != nil {
resp.Err = err
}

for _, f := range r.client.afterResponse {
Expand Down
16 changes: 10 additions & 6 deletions response.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ func (r *Response) ToString() (string, error) {
}

// ToBytes returns the response body as []byte, read body if not have been read.
func (r *Response) ToBytes() ([]byte, error) {
func (r *Response) ToBytes() (body []byte, err error) {
if r.Err != nil {
return nil, r.Err
}
Expand All @@ -167,15 +167,19 @@ func (r *Response) ToBytes() ([]byte, error) {
if r.Response == nil || r.Response.Body == nil {
return []byte{}, nil
}
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body)
defer func() {
r.Body.Close()
if err != nil {
r.Err = err
}
r.body = body
}()
body, err = ioutil.ReadAll(r.Body)
r.setReceivedAt()
r.body = body
if err == nil && r.Request.client.responseBodyTransformer != nil {
body, err = r.Request.client.responseBodyTransformer(body, r.Request, r)
r.body = body
}
return body, err
return
}

// Dump return the string content that have been dumped for the request.
Expand Down

0 comments on commit 28436eb

Please sign in to comment.