fix: improve codersdk error messages when not JSON (#4495)

This commit is contained in:
Dean Sheather
2022-10-21 23:36:31 +00:00
committed by GitHub
parent 7bc5b89f7a
commit d0fb054a55
4 changed files with 233 additions and 11 deletions
+31 -9
View File
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"strings"
@@ -122,33 +123,54 @@ func readBodyAsError(res *http.Response) error {
helper = "Try logging in using 'coder login <url>'."
}
if strings.HasPrefix(contentType, "text/plain") {
resp, err := io.ReadAll(res.Body)
if err != nil {
return xerrors.Errorf("read body: %w", err)
resp, err := io.ReadAll(res.Body)
if err != nil {
return xerrors.Errorf("read body: %w", err)
}
mimeType, _, err := mime.ParseMediaType(contentType)
if err != nil {
mimeType = strings.TrimSpace(strings.Split(contentType, ";")[0])
}
if mimeType != "application/json" {
if len(resp) > 1024 {
resp = append(resp[:1024], []byte("...")...)
}
if len(resp) == 0 {
resp = []byte("no response body")
}
return &Error{
statusCode: res.StatusCode,
Response: Response{
Message: string(resp),
Message: "unexpected non-JSON response",
Detail: string(resp),
},
Helper: helper,
}
}
//nolint:varnamelen
var m Response
err := json.NewDecoder(res.Body).Decode(&m)
err = json.NewDecoder(bytes.NewBuffer(resp)).Decode(&m)
if err != nil {
if errors.Is(err, io.EOF) {
// If no body is sent, we'll just provide the status code.
return &Error{
statusCode: res.StatusCode,
Helper: helper,
Response: Response{
Message: "empty response body",
},
Helper: helper,
}
}
return xerrors.Errorf("decode body: %w", err)
}
if m.Message == "" {
if len(resp) > 1024 {
resp = append(resp[:1024], []byte("...")...)
}
m.Message = fmt.Sprintf("unexpected status code %d, response has no message", res.StatusCode)
m.Detail = string(resp)
}
return &Error{
Response: m,
statusCode: res.StatusCode,