Skip to content

Commit

Permalink
v2 - Fix incorrectTypeForFlagError for unknowns
Browse files Browse the repository at this point in the history
The `reflect` package doesn't always know what to call a type in
`(reflect.Type).Name()`, but `fmt.Errorf("%T")` always gets it right.
Use that so we get actionable error messages.
  • Loading branch information
danhunsaker committed Mar 25, 2023
1 parent 560c87b commit ef7074a
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 8 deletions.
9 changes: 1 addition & 8 deletions altsrc/map_input_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package altsrc
import (
"fmt"
"math"
"reflect"
"strings"
"time"

Expand Down Expand Up @@ -471,11 +470,5 @@ func (fsm *MapInputSource) isSet(name string) bool {
}

func incorrectTypeForFlagError(name, expectedTypeName string, value interface{}) error {
valueType := reflect.TypeOf(value)
valueTypeName := ""
if valueType != nil {
valueTypeName = valueType.Name()
}

return fmt.Errorf("Mismatched type for flag '%s'. Expected '%s' but actual is '%s'", name, expectedTypeName, valueTypeName)
return fmt.Errorf("Mismatched type for flag '%s'. Expected '%s' but actual is '%T'", name, expectedTypeName, value)
}
6 changes: 6 additions & 0 deletions altsrc/map_input_source_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package altsrc

import (
"fmt"
"testing"
"time"
)
Expand Down Expand Up @@ -33,3 +34,8 @@ func TestMapInputSource_Int64Slice(t *testing.T) {
expect(t, []int64{1, 2, 3}, d)
expect(t, nil, err)
}

func TestMapInputSource_IncorrectFlagTypeError(t *testing.T) {
var testVal *bool
expect(t, incorrectTypeForFlagError("test", "bool", testVal), fmt.Errorf("Mismatched type for flag 'test'. Expected 'bool' but actual is '*bool'"))
}

0 comments on commit ef7074a

Please sign in to comment.