File tree Expand file tree Collapse file tree 3 files changed +30
-2
lines changed Expand file tree Collapse file tree 3 files changed +30
-2
lines changed Original file line number Diff line number Diff line change @@ -14,10 +14,15 @@ var ErrNoRootCommand = errors.New("no root command provided")
14
14
// App represents a command line application.
15
15
type App struct {
16
16
CobraProvider
17
+ ErrorHandler
17
18
Exit func (code int )
18
19
root * cobra.Command
19
20
}
20
21
22
+ // ErrorHandler is a function that will be used to handle the errors. If true
23
+ // is returned, the default error handling will not be used.
24
+ type ErrorHandler func (err error ) bool
25
+
21
26
// CobraProvider is used to provide a Cobra command.
22
27
type CobraProvider interface {
23
28
Command () * cobra.Command
@@ -33,8 +38,12 @@ func New(cp CobraProvider) *App {
33
38
34
39
// ExecuteOrDie will execute the application or perform os.Exit in case of error.
35
40
func (a * App ) ExecuteOrDie (options ... Option ) {
36
- if err := a .Execute (options ... ); err != nil {
37
- a .Exit (retcode .Calc (err ))
41
+ err := a .Execute (options ... )
42
+ if err == nil {
43
+ return
44
+ }
45
+ if a .ErrorHandler == nil || ! a .ErrorHandler (err ) {
46
+ a .defaultErrorHandler (err )
38
47
}
39
48
}
40
49
@@ -64,3 +73,9 @@ func (a *App) init() error {
64
73
}
65
74
return nil
66
75
}
76
+
77
+ func (a * App ) defaultErrorHandler (err error ) {
78
+ if err != nil {
79
+ a .Exit (retcode .Calc (err ))
80
+ }
81
+ }
Original file line number Diff line number Diff line change @@ -14,6 +14,7 @@ import (
14
14
func TestExecuteOrDie (t * testing.T ) {
15
15
var buf bytes.Buffer
16
16
var retcode int
17
+ var err error
17
18
commandline .New (new (testApp )).ExecuteOrDie (
18
19
commandline .WithCommand (func (cmd * cobra.Command ) {
19
20
cmd .SetOut (& buf )
@@ -23,9 +24,14 @@ func TestExecuteOrDie(t *testing.T) {
23
24
commandline .WithExit (func (code int ) {
24
25
retcode = code
25
26
}),
27
+ commandline .WithErrorHandler (func (merr error ) bool {
28
+ err = merr
29
+ return false
30
+ }),
26
31
)
27
32
assert .Equal (t , `example Input: ["arg1" "arg2"]` , buf .String ())
28
33
assert .Equal (t , 133 , retcode )
34
+ assert .Assert (t , err != nil )
29
35
}
30
36
31
37
func TestExit (t * testing.T ) {
Original file line number Diff line number Diff line change @@ -41,6 +41,13 @@ func WithCommand(fn func(cmd *cobra.Command)) Option {
41
41
}
42
42
}
43
43
44
+ // WithErrorHandler will allow changing the default error handler.
45
+ func WithErrorHandler (fn ErrorHandler ) Option {
46
+ return func (app * App ) {
47
+ app .ErrorHandler = fn
48
+ }
49
+ }
50
+
44
51
// WithExit creates an option which sets the exit function.
45
52
func WithExit (fn func (code int )) Option {
46
53
return func (app * App ) {
You can’t perform that action at this time.
0 commit comments