diff --git a/client.go b/client.go index 765f96ae..b4b46235 100644 --- a/client.go +++ b/client.go @@ -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 { diff --git a/response.go b/response.go index 66af8364..6cbcb657 100644 --- a/response.go +++ b/response.go @@ -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 } @@ -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.