mirror of
https://github.com/coder/coder.git
synced 2026-09-24 15:04:27 +08:00
fix: improve codersdk error messages when not JSON (#4495)
This commit is contained in:
+31
-9
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user