diff --git a/apis/field_error.go b/apis/field_error.go index 4ae02bc1e..e3c3ae4e8 100644 --- a/apis/field_error.go +++ b/apis/field_error.go @@ -192,7 +192,7 @@ func asKey(key string) string { // err([0]).ViaField(bar).ViaField(foo) -> foo.bar.[0] converts to foo.bar[0] // err(bar).ViaIndex(0).ViaField(foo) -> foo.[0].bar converts to foo[0].bar // err(bar).ViaField(foo).ViaIndex(0) -> [0].foo.bar converts to [0].foo.bar -// err(bar).ViaIndex(0).ViaIndex[1].ViaField(foo) -> foo.[1].[0].bar converts to foo[1][0].bar +// err(bar).ViaIndex(0).ViaIndex(1).ViaField(foo) -> foo.[1].[0].bar converts to foo[1][0].bar func flatten(path []string) string { var newPath []string for _, part := range path { @@ -300,6 +300,12 @@ func ErrDisallowedFields(fieldPaths ...string) *FieldError { } } +// ErrInvalidArrayValue consturcts a FieldError for a repetetive `field` +// at `index` that has received an invalid string value. +func ErrInvalidArrayValue(value, field string, index int) *FieldError { + return ErrInvalidValue(value, CurrentField).ViaFieldIndex(field, index) +} + // ErrInvalidValue constructs a FieldError for a field that has received an // invalid string value. func ErrInvalidValue(value, fieldPath string) *FieldError { diff --git a/apis/field_error_test.go b/apis/field_error_test.go index 1b80fff8b..7e6407ab4 100644 --- a/apis/field_error_test.go +++ b/apis/field_error_test.go @@ -21,6 +21,8 @@ import ( "strconv" "strings" "testing" + + "github.com/google/go-cmp/cmp" ) func TestFieldError(t *testing.T) { @@ -389,6 +391,12 @@ can not use @, do not try`, return err }(), want: "invalid field(s): jar[0][E].baz[1].bar[A].faa, jar[0][E].baz[1].bar[A].foo", + }, { + name: "leaf field error with index", + err: func() *FieldError { + return ErrInvalidArrayValue("kapot", "indexed", 5) + }(), + want: `invalid value "kapot": indexed[5]`, }, { name: "nil propagation", err: nil, @@ -421,7 +429,7 @@ can not use @, do not try`, if test.want != "" { if got, want := fe.Error(), test.want; got != want { - t.Errorf("%s: Error() = %v, wanted %v", test.name, got, want) +t.Errorf("%s: Error() = %q, wanted %q, diff: %s", test.name, got, want, cmp.Diff(got, want)) } } else if fe != nil { t.Errorf("%s: ViaField() = %v, wanted nil", test.name, fe)