Skip to content

Commit

Permalink
fix: NPE due to checking if error is nil when it can be a value
Browse files Browse the repository at this point in the history
Fixes #468
  • Loading branch information
alecthomas committed Nov 5, 2024
1 parent c90c673 commit f388f6c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
2 changes: 1 addition & 1 deletion callbacks.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func callFunction(f reflect.Value, bindings bindings) error {
return err
}
ferr := out[0]
if ferrv := reflect.ValueOf(ferr); !ferrv.IsValid() || ferrv.IsNil() {
if ferrv := reflect.ValueOf(ferr); !ferrv.IsValid() || ((ferrv.Kind() == reflect.Interface || ferrv.Kind() == reflect.Pointer) && ferrv.IsNil()) {
return nil
}
return ferr.(error) //nolint:forcetypeassert
Expand Down
19 changes: 19 additions & 0 deletions options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,22 @@ func TestFlagNamer(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, "SOMEFLAG", app.Model.Flags[1].Name)
}

type npError string

func (e npError) Error() string {
return "ERROR: " + string(e)
}

func TestCallbackNonPointerError(t *testing.T) {
method := func() error {
return npError("failed")
}

var cli struct{}

p, err := New(&cli)
assert.NoError(t, err)
err = callFunction(reflect.ValueOf(method), p.bindings)
assert.EqualError(t, err, "ERROR: failed")
}

0 comments on commit f388f6c

Please sign in to comment.