From b448e1c2cfd852a62c881e237342de63a01d7d8a Mon Sep 17 00:00:00 2001 From: Chris Suszynski Date: Fri, 18 Oct 2024 17:34:18 +0200 Subject: [PATCH] :gift_heart: Allow error handlers to access the Cobra' command object (#4) Allow error handlers to access the Cobra' command object --- app.go | 7 ++++--- app_test.go | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/app.go b/app.go index 4224f83..ed050a0 100644 --- a/app.go +++ b/app.go @@ -20,8 +20,9 @@ type App struct { } // ErrorHandler is a function that will be used to handle the errors. If true -// is returned, the default error handling will not be used. -type ErrorHandler func(err error) bool +// is returned, the default error handling will not be used. The Cobra's command +// passed to the error handler is the command that thrown the error. +type ErrorHandler func(err error, cmd *cobra.Command) bool // CobraProvider is used to provide a Cobra command. type CobraProvider interface { @@ -42,7 +43,7 @@ func (a *App) ExecuteOrDie(options ...Option) { if err == nil { return } - if a.ErrorHandler == nil || !a.ErrorHandler(err) { + if a.ErrorHandler == nil || !a.ErrorHandler(err, a.root) { a.defaultErrorHandler(err) } } diff --git a/app_test.go b/app_test.go index e079251..1a93218 100644 --- a/app_test.go +++ b/app_test.go @@ -24,7 +24,7 @@ func TestExecuteOrDie(t *testing.T) { commandline.WithExit(func(code int) { retcode = code }), - commandline.WithErrorHandler(func(merr error) bool { + commandline.WithErrorHandler(func(merr error, _ *cobra.Command) bool { err = merr return false }),