Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion mapstructure.go
Original file line number Diff line number Diff line change
Expand Up @@ -1605,8 +1605,14 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
}
sort.Strings(keys)

// Improve error message when name is empty by showing the target struct type
// in the case where it is empty for embedded structs.
errorName := name
if errorName == "" {
errorName = val.Type().String()
}
errs = append(errs, newDecodeError(
name,
errorName,
fmt.Errorf("has invalid keys: %s", strings.Join(keys, ", ")),
))
}
Expand Down
55 changes: 55 additions & 0 deletions mapstructure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3560,3 +3560,58 @@ func uintPtr(v uint) *uint { return &v }
func boolPtr(v bool) *bool { return &v }
func floatPtr(v float64) *float64 { return &v }
func interfacePtr(v any) *any { return &v }

// Test struct for embedded error message testing
type TestDatabaseConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
Username string `mapstructure:"username"`
}

type TestServerConfig struct {
TestDatabaseConfig `mapstructure:",squash"`
AppName string `mapstructure:"app_name"`
Debug bool `mapstructure:"debug"`
}

func TestDecoder_ErrorUnused_EmbeddedStruct_QualifiedTypeName(t *testing.T) {
t.Parallel()

// Input with an invalid key that should cause an error
input := map[string]any{
"host": "localhost",
"port": 5432,
"username": "admin",
"app_name": "myapp",
"debug": true,
"invalid_key": "this should cause an error", // This key doesn't exist in the struct
}

var config TestServerConfig

decoder, err := NewDecoder(&DecoderConfig{
ErrorUnused: true, // Enable error on unused keys
Result: &config,
})
if err != nil {
t.Fatalf("err: %s", err)
}

err = decoder.Decode(input)
if err == nil {
t.Fatal("expected error due to unused keys")
}

errorMessage := err.Error()
t.Logf("Error message: %s", errorMessage)

// Check that the error message contains the qualified struct type name
if !strings.Contains(errorMessage, "'mapstructure.TestServerConfig'") {
t.Errorf("Expected error message to contain qualified struct type 'mapstructure.TestServerConfig', got: %s", errorMessage)
}

// Check that unused keys are mentioned
if !strings.Contains(errorMessage, "invalid_key") {
t.Errorf("Expected error message to contain 'invalid_key', got: %s", errorMessage)
}
}