Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow Ignoring Usage Errors #656

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1306,6 +1306,7 @@ func main() {
fmt.Fprintf(c.App.Writer, "WRONG: %#v\n", err)
return nil
},
IgnoreUsageError: true,
Action: func(c *cli.Context) error {
cli.DefaultAppComplete(c)
cli.HandleExitCoder(errors.New("not an exit coder, though"))
Expand Down
4 changes: 3 additions & 1 deletion app.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ type App struct {
Action ActionFunc
// Execute this function if the proper command cannot be found
CommandNotFound CommandNotFoundFunc
// Ignore usage errors to be handled later
IgnoreUsageError bool
// Execute this function if an usage error occurs
OnUsageError OnUsageErrorFunc
// Compilation date
Expand Down Expand Up @@ -187,7 +189,7 @@ func (a *App) Run(arguments []string) (err error) {
}
}

if err != nil {
if err != nil && !a.IgnoreUsageError {
if a.OnUsageError != nil {
err := a.OnUsageError(context, err, false)
HandleExitCoder(err)
Expand Down
21 changes: 21 additions & 0 deletions app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1485,3 +1485,24 @@ func TestApp_OnUsageError_WithWrongFlagValue_ForSubcommand(t *testing.T) {
t.Errorf("Expect an intercepted error, but got \"%v\"", err)
}
}

func TestApp_IgnoreOnUsageError(t *testing.T) {
app := &App{
Flags: []Flag{
&IntFlag{Name: "flag"},
},
Action: func(c *Context) error {
return nil
},
OnUsageError: func(c *Context, err error, isSubcommand bool) error {
t.Fatalf("Shouldn't throw error")
return errors.New("intercepted: " + err.Error())
},
IgnoreUsageError: true,
}

err := app.Run([]string{"foo", "--wrong-flag"})
if err != nil {
t.Fatalf("expected to not receive error, but got: \"%v\"", err)
}
}