Skip to content

Commit

Permalink
Simplify type switch
Browse files Browse the repository at this point in the history
  • Loading branch information
jotaen committed Nov 14, 2024
1 parent f9ae0b6 commit 222fced
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 13 deletions.
29 changes: 16 additions & 13 deletions klog/app/main/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ func Run(homeDir app.File, meta app.Meta, config app.Config, args []string) (int
}),
)
if nErr != nil {
// This code branch is not expected to be invoked in practice. If it were to
// happen, that most likely indicates a bug in the app setup.
return app.GENERAL_ERROR.ToInt(), errors.New("Internal error: " + nErr.Error())
}

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

rErr := kongCtx.Run()
if rErr != nil {
if errors.Is(rErr, app.NewParserErrors(nil)) {
var e app.ParserErrors
errors.As(rErr, &e)
return e.Code().ToInt(), util.PrettifyParsingError(e, styler)
} else if errors.Is(rErr, app.NewError("", "", nil)) {
var e app.Error
errors.As(rErr, &e)
return e.Code().ToInt(), util.PrettifyAppError(e, config.IsDebug.Value())
} else {
return app.GENERAL_ERROR.ToInt(), errors.New("Error: " + rErr.Error())
}
parserErrors := app.NewParserErrors(nil)
appError := app.NewError("", "", nil)

switch {
case rErr == nil:
return 0, nil
case errors.As(rErr, &parserErrors):
return parserErrors.Code().ToInt(), util.PrettifyParsingError(parserErrors, styler)
case errors.As(rErr, &appError):
return appError.Code().ToInt(), util.PrettifyAppError(appError, config.IsDebug.Value())
default:
// This is just a fallback clause; this code branch is not expected to be
// invoked in practice.
return app.GENERAL_ERROR.ToInt(), errors.New("Error: " + rErr.Error())
}
return 0, nil
}
10 changes: 10 additions & 0 deletions klog/app/main/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ func TestHandleInputFiles(t *testing.T) {
assert.True(t, strings.Contains(out[1], "#foo 2h"), out)
}

func TestHandlesInvocationErrors(t *testing.T) {
out := (&Env{
files: map[string]string{},
}).run(
[]string{"print", "--foo"},
)
// Invocation error: unknown flag --foo
assert.True(t, strings.Contains(out[0], "Invocation error: unknown flag --foo"), out)
}

func TestPrintAppErrors(t *testing.T) {
out := (&Env{
files: map[string]string{
Expand Down

0 comments on commit 222fced

Please sign in to comment.