MCPcopy Index your code
hub / github.com/coder/coder / errorExample

Method errorExample

cli/exp_errors.go:15–127  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

13)
14
15func (RootCmd) errorExample() *serpent.Command {
16 errorCmd := func(use string, err error) *serpent.Command {
17 return &serpent.Command{
18 Use: use,
19 Handler: func(_ *serpent.Invocation) error {
20 return err
21 },
22 }
23 }
24
25 // Make an api error
26 recorder := httptest.NewRecorder()
27 recorder.WriteHeader(http.StatusBadRequest)
28 resp := recorder.Result()
29 _ = resp.Body.Close()
30 resp.Request, _ = http.NewRequest(http.MethodPost, "http://example.com", nil)
31 apiError := codersdk.ReadBodyAsError(resp)
32 //nolint:errorlint,forcetypeassert
33 apiError.(*codersdk.Error).Response = codersdk.Response{
34 Message: "Top level sdk error message.",
35 Detail: "magic dust unavailable, please try again later",
36 Validations: []codersdk.ValidationError{
37 {
38 Field: "region",
39 Detail: "magic dust is not available in your region",
40 },
41 },
42 }
43 //nolint:errorlint,forcetypeassert
44 apiError.(*codersdk.Error).Helper = "Have you tried turning it off and on again?"
45
46 //nolint:errorlint,forcetypeassert
47 cpy := *apiError.(*codersdk.Error)
48 apiErrorNoHelper := &cpy
49 apiErrorNoHelper.Helper = ""
50
51 // Some flags
52 var magicWord serpent.String
53
54 cmd := &serpent.Command{
55 Use: "example-error",
56 Short: "Shows what different error messages look like",
57 Long: "This command is pretty pointless, but without it testing errors is" +
58 "difficult to visually inspect. Error message formatting is inherently" +
59 "visual, so we need a way to quickly see what they look like.",
60 Handler: func(inv *serpent.Invocation) error {
61 return inv.Command.HelpHandler(inv)
62 },
63 Children: []*serpent.Command{
64 // Typical codersdk api error
65 errorCmd("api", apiError),
66
67 // Typical cli error
68 errorCmd("cmd", xerrors.Errorf("some error: %w", errorWithStackTrace())),
69
70 // A multi-error
71 {
72 Use: "multi-error",

Callers 1

AGPLExperimentalMethod · 0.95

Calls 7

ReadBodyAsErrorFunction · 0.92
errorWithStackTraceFunction · 0.85
CloseMethod · 0.65
ValidateMethod · 0.65
WriteHeaderMethod · 0.45
ResultMethod · 0.45
ErrorfMethod · 0.45

Tested by

no test coverage detected