Skip to content

Commit

Permalink
Mention all missed but required fields in the error (#143)
Browse files Browse the repository at this point in the history
  • Loading branch information
zhezhel authored Sep 3, 2023
1 parent 27d6984 commit 3b3b803
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
11 changes: 9 additions & 2 deletions aconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,15 +261,22 @@ func (l *Loader) loadSources() error {
}

func (l *Loader) checkRequired() error {
missedFields := []string{}
for _, field := range l.fields {
if field.isSet {
continue
}
if field.isRequired || l.config.AllFieldRequired {
return fmt.Errorf("field %s is required but not set", field.name)
missedFields = append(missedFields, field.name)
}
}
return nil
if len(missedFields) == 0 {
return nil
}
if len(missedFields) == 1 {
return fmt.Errorf("field %s is required but not set", missedFields[0])
}
return fmt.Errorf("fields %s are required but not set", strings.Join(missedFields, ","))
}

func (l *Loader) loadDefaults() error {
Expand Down
32 changes: 32 additions & 0 deletions aconfig_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1087,6 +1087,38 @@ func TestBadRequiredTag(t *testing.T) {
f(&TestConfig{})
}

func TestMissingFieldWithRequiredTag(t *testing.T) {
cfg := struct {
Field1 string `required:"true"`
}{}
loader := LoaderFor(&cfg, Config{
SkipFlags: true,
})

err := loader.Load()

want := "load config: field Field1 is required but not set"
if err.Error() != want {
t.Fatalf("got %v, want %v", err, want)
}
}
func TestMissingFieldsWithRequiredTag(t *testing.T) {
cfg := struct {
Field1 string `required:"true"`
Field2 string `required:"true"`
}{}
loader := LoaderFor(&cfg, Config{
SkipFlags: true,
})

err := loader.Load()

want := "load config: fields Field1,Field2 are required but not set"
if err.Error() != want {
t.Fatalf("got %v, want %v", err, want)
}
}

func int32Ptr(a int32) *int32 {
return &a
}
Expand Down

0 comments on commit 3b3b803

Please sign in to comment.