bug: Cleaner error message for non logged-in users (#1670)

* add helper text to unauthorized error messages

* fix lint error, add unit tests

* fix test name

* fix test name

* fix lint errors in test

* add unauthorized test for templates create

* remove unnecessary variable

* remove Error struct, change error message

* change [url] to <url>
This commit is contained in:
Abhineet Jain
2022-05-23 14:51:49 -04:00
committed by GitHub
parent c543fca92f
commit 4a78bade6d
4 changed files with 79 additions and 14 deletions

View File

@ -125,6 +125,14 @@ func (c *Client) dialWebsocket(ctx context.Context, path string) (*websocket.Con
// wraps it in a codersdk.Error type for easy marshaling.
func readBodyAsError(res *http.Response) error {
contentType := res.Header.Get("Content-Type")
var helper string
if res.StatusCode == http.StatusUnauthorized {
// 401 means the user is not logged in
// 403 would mean that the user is not authorized
helper = "Try logging in using 'coder login <url>'."
}
if strings.HasPrefix(contentType, "text/plain") {
resp, err := io.ReadAll(res.Body)
if err != nil {
@ -135,6 +143,7 @@ func readBodyAsError(res *http.Response) error {
Response: httpapi.Response{
Message: string(resp),
},
Helper: helper,
}
}
@ -146,6 +155,7 @@ func readBodyAsError(res *http.Response) error {
// If no body is sent, we'll just provide the status code.
return &Error{
statusCode: res.StatusCode,
Helper: helper,
}
}
return xerrors.Errorf("decode body: %w", err)
@ -153,6 +163,7 @@ func readBodyAsError(res *http.Response) error {
return &Error{
Response: m,
statusCode: res.StatusCode,
Helper: helper,
}
}
@ -162,6 +173,8 @@ type Error struct {
httpapi.Response
statusCode int
Helper string
}
func (e *Error) StatusCode() int {
@ -171,6 +184,9 @@ func (e *Error) StatusCode() int {
func (e *Error) Error() string {
var builder strings.Builder
_, _ = fmt.Fprintf(&builder, "status code %d: %s", e.statusCode, e.Message)
if e.Helper != "" {
_, _ = fmt.Fprintf(&builder, ": %s", e.Helper)
}
for _, err := range e.Errors {
_, _ = fmt.Fprintf(&builder, "\n\t%s: %s", err.Field, err.Detail)
}