Skip to content

Commit 222fced

Browse files
committed
Simplify type switch
1 parent f9ae0b6 commit 222fced

File tree

2 files changed

+26
-13
lines changed

2 files changed

+26
-13
lines changed

klog/app/main/cli.go

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,8 @@ func Run(homeDir app.File, meta app.Meta, config app.Config, args []string) (int
6767
}),
6868
)
6969
if nErr != nil {
70+
// This code branch is not expected to be invoked in practice. If it were to
71+
// happen, that most likely indicates a bug in the app setup.
7072
return app.GENERAL_ERROR.ToInt(), errors.New("Internal error: " + nErr.Error())
7173
}
7274

@@ -95,18 +97,19 @@ func Run(homeDir app.File, meta app.Meta, config app.Config, args []string) (int
9597
kongCtx.BindTo(ctx, (*app.Context)(nil))
9698

9799
rErr := kongCtx.Run()
98-
if rErr != nil {
99-
if errors.Is(rErr, app.NewParserErrors(nil)) {
100-
var e app.ParserErrors
101-
errors.As(rErr, &e)
102-
return e.Code().ToInt(), util.PrettifyParsingError(e, styler)
103-
} else if errors.Is(rErr, app.NewError("", "", nil)) {
104-
var e app.Error
105-
errors.As(rErr, &e)
106-
return e.Code().ToInt(), util.PrettifyAppError(e, config.IsDebug.Value())
107-
} else {
108-
return app.GENERAL_ERROR.ToInt(), errors.New("Error: " + rErr.Error())
109-
}
100+
parserErrors := app.NewParserErrors(nil)
101+
appError := app.NewError("", "", nil)
102+
103+
switch {
104+
case rErr == nil:
105+
return 0, nil
106+
case errors.As(rErr, &parserErrors):
107+
return parserErrors.Code().ToInt(), util.PrettifyParsingError(parserErrors, styler)
108+
case errors.As(rErr, &appError):
109+
return appError.Code().ToInt(), util.PrettifyAppError(appError, config.IsDebug.Value())
110+
default:
111+
// This is just a fallback clause; this code branch is not expected to be
112+
// invoked in practice.
113+
return app.GENERAL_ERROR.ToInt(), errors.New("Error: " + rErr.Error())
110114
}
111-
return 0, nil
112115
}

klog/app/main/cli_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,16 @@ func TestHandleInputFiles(t *testing.T) {
2323
assert.True(t, strings.Contains(out[1], "#foo 2h"), out)
2424
}
2525

26+
func TestHandlesInvocationErrors(t *testing.T) {
27+
out := (&Env{
28+
files: map[string]string{},
29+
}).run(
30+
[]string{"print", "--foo"},
31+
)
32+
// Invocation error: unknown flag --foo
33+
assert.True(t, strings.Contains(out[0], "Invocation error: unknown flag --foo"), out)
34+
}
35+
2636
func TestPrintAppErrors(t *testing.T) {
2737
out := (&Env{
2838
files: map[string]string{

0 commit comments

Comments
 (0)