Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
chore: add command to easily visualize different errors
  • Loading branch information
Emyrk committed Sep 29, 2023
commit f2cbe7760970e2da0827eac0ac82110f1fe72441
83 changes: 83 additions & 0 deletions cli/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package cli

import (
"io"
"os"

"github.com/coder/coder/v2/cli/clibase"
"github.com/coder/coder/v2/codersdk"
"golang.org/x/xerrors"
)

func (r *RootCmd) errorExample() *clibase.Cmd {
errorCmd := func(use string, err error) *clibase.Cmd {
return &clibase.Cmd{
Use: use,
Handler: func(inv *clibase.Invocation) error {
return err
},
}
}

cmd := &clibase.Cmd{
Use: "example-error",
Short: "Shows what different error messages look like",
Long: "This command is pretty pointless, but without it testing errors is" +
"difficult to visually inspect. Error message formatting is inherently" +
"visual, so we need a way to quickly see what they look like.",
Handler: func(inv *clibase.Invocation) error {
return inv.Command.HelpHandler(inv)
},
Children: []*clibase.Cmd{
// Typical codersdk error
errorCmd("sdk", &codersdk.Error{
Response: codersdk.Response{
Message: "Top level sdk error message.",
Detail: "magic dust unavailable, please try again later",
Validations: []codersdk.ValidationError{
{
Field: "region",
Detail: "magic dust is not available in your region",
},
},
},
Helper: "Have you tried turning it off and on again?",
}),

// Typical cli error
errorCmd("cmd", xerrors.Errorf("some error: %w", errorWithStackTrace())),

// A multi-error
{
Use: "multi-error",
Handler: func(inv *clibase.Invocation) error {
// Closing the stdin file descriptor will cause the next close
// to fail. This is joined to the returned Command error.
if f, ok := inv.Stdin.(*os.File); ok {
_ = f.Close()
}

return xerrors.Errorf("some error: %w", errorWithStackTrace())
},
},
},
}

return cmd
}

type errorClose struct {
io.ReadCloser
}

func (e errorClose) Close() error {
err := e.ReadCloser.Close()
if err == nil {
return xerrors.Errorf("always close error")
}
return err
}

func errorWithStackTrace() error {
return xerrors.Errorf("function decided not to work, and it never will")
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Re: lines 103 to 103]

Nifty

See this comment inline on Graphite.

1 change: 1 addition & 0 deletions cli/exp.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ func (r *RootCmd) expCmd() *clibase.Cmd {
Hidden: true,
Children: []*clibase.Cmd{
r.scaletestCmd(),
r.errorExample(),
},
}
return cmd
Expand Down