Skip to content

Commit

Permalink
[chore] Remove the top level error if it indicates an empty name (#9763)
Browse files Browse the repository at this point in the history
This is a split of #9750 that tries to work around mapstructure, which
wraps an error around a decoding error.

In the case when an error is returned from a top level construct, we get
a not so helpful message that says:
```
error decoding '': error running encode hook: marshaling error
```

With this change, the error is unwrapped, giving the following string
representation:
```
error running encode hook: marshaling error
```

Because #9750 enforces going through mapstructure, it would change
errors returned with this not-so-helpful preamble. Adding this removes
the problem.
  • Loading branch information
atoulme committed Mar 14, 2024
1 parent 3cb1250 commit c62b80d
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
10 changes: 9 additions & 1 deletion confmap/confmap.go
Expand Up @@ -5,8 +5,10 @@ package confmap // import "go.opentelemetry.io/collector/confmap"

import (
"encoding"
"errors"
"fmt"
"reflect"
"strings"

"github.com/go-viper/mapstructure/v2"
"github.com/knadh/koanf/maps"
Expand Down Expand Up @@ -167,7 +169,13 @@ func decodeConfig(m *Conf, result any, errorUnused bool) error {
if err != nil {
return err
}
return decoder.Decode(m.ToStringMap())
if err = decoder.Decode(m.ToStringMap()); err != nil {
if strings.HasPrefix(err.Error(), "error decoding ''") {
return errors.Unwrap(err)
}
return err
}
return nil
}

// encoderConfig returns a default encoder.EncoderConfig that includes
Expand Down
4 changes: 2 additions & 2 deletions confmap/confmap_test.go
Expand Up @@ -450,7 +450,7 @@ func TestEmbeddedUnmarshalerError(t *testing.T) {
})

tc := &testConfigWithEmbeddedError{}
assert.EqualError(t, cfgMap.Unmarshal(tc), "error decoding '': embedded error")
assert.EqualError(t, cfgMap.Unmarshal(tc), "embedded error")
}

func TestEmbeddedMarshalerError(t *testing.T) {
Expand All @@ -462,7 +462,7 @@ func TestEmbeddedMarshalerError(t *testing.T) {
})

tc := &testConfigWithMarshalError{}
assert.EqualError(t, cfgMap.Unmarshal(tc), "error decoding '': error running encode hook: marshaling error")
assert.EqualError(t, cfgMap.Unmarshal(tc), "error running encode hook: marshaling error")
}

func TestUnmarshalerKeepAlreadyInitialized(t *testing.T) {
Expand Down

0 comments on commit c62b80d

Please sign in to comment.