Skip to content

Commit 1b8b985

Browse files
Leo Diaz Sanchezncw
authored andcommitted
append response body to error if it exists
1 parent d0b774e commit 1b8b985

File tree

1 file changed

+43
-2
lines changed

1 file changed

+43
-2
lines changed

swift.go

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -372,22 +372,63 @@ func drainAndClose(rd io.ReadCloser, err *error) {
372372
}
373373

374374
// parseHeaders checks a response for errors and translates into
375-
// standard errors if necessary. If an error is returned, resp.Body
375+
// standard errors if necessary. If an error message is present in the response body,
376+
// it will be included in the error. If an error is returned, resp.Body
376377
// has been drained and closed.
377378
func (c *Connection) parseHeaders(resp *http.Response, errorMap errorMap) error {
378379
if errorMap != nil {
379380
if err, ok := errorMap[resp.StatusCode]; ok {
381+
err = appendResponseBodyToError(resp, err)
380382
drainAndClose(resp.Body, nil)
381383
return err
382384
}
383385
}
384386
if resp.StatusCode < 200 || resp.StatusCode > 299 {
387+
var err error = newErrorf(resp.StatusCode, "HTTP Error: %d: %s", resp.StatusCode, resp.Status)
388+
err = appendResponseBodyToError(resp, err)
385389
drainAndClose(resp.Body, nil)
386-
return newErrorf(resp.StatusCode, "HTTP Error: %d: %s", resp.StatusCode, resp.Status)
390+
return err
387391
}
388392
return nil
389393
}
390394

395+
// appendResponseBodyToError tries to append the response body to the error message.
396+
func appendResponseBodyToError(resp *http.Response, err error) error {
397+
if resp == nil || resp.Body == nil || err == nil {
398+
return err
399+
}
400+
401+
if resp.Header.Get("Content-Length") == "0" {
402+
return err
403+
}
404+
405+
ct := resp.Header.Get("Content-Type")
406+
if ct == "" {
407+
return err
408+
}
409+
410+
lowerCT := strings.ToLower(ct)
411+
if !(strings.Contains(lowerCT, "text") ||
412+
strings.Contains(lowerCT, "json") ||
413+
strings.Contains(lowerCT, "xml") ||
414+
strings.Contains(lowerCT, "html") ||
415+
strings.Contains(lowerCT, "plain")) {
416+
return err
417+
}
418+
419+
body, readErr := io.ReadAll(resp.Body)
420+
if readErr != nil || len(body) == 0 {
421+
return err
422+
}
423+
424+
trimmed := strings.TrimSpace(string(body))
425+
if trimmed == "" {
426+
return err
427+
}
428+
429+
return fmt.Errorf("%w: %s", err, trimmed)
430+
}
431+
391432
// readHeaders returns a Headers object from the http.Response.
392433
//
393434
// If it receives multiple values for a key (which should never

0 commit comments

Comments
 (0)