Skip to content

Commit 3ea155d

Browse files
committed
[confmap] Add error hint when invalid YAML was passed
1 parent 2447a81 commit 3ea155d

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

confmap/provider.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,13 +100,15 @@ type ChangeEvent struct {
100100
// Retrieved holds the result of a call to the Retrieve method of a Provider object.
101101
type Retrieved struct {
102102
rawConf any
103+
errorHint error
103104
closeFunc CloseFunc
104105

105106
stringRepresentation string
106107
isSetString bool
107108
}
108109

109110
type retrievedSettings struct {
111+
errorHint error
110112
stringRepresentation string
111113
isSetString bool
112114
closeFunc CloseFunc
@@ -138,6 +140,12 @@ func withStringRepresentation(stringRepresentation string) RetrievedOption {
138140
})
139141
}
140142

143+
func withErrorHint(errorHint error) RetrievedOption {
144+
return retrievedOptionFunc(func(settings *retrievedSettings) {
145+
settings.errorHint = errorHint
146+
})
147+
}
148+
141149
// NewRetrievedFromYAML returns a new Retrieved instance that contains the deserialized data from the yaml bytes.
142150
// * yamlBytes the yaml bytes that will be deserialized.
143151
// * opts specifies options associated with this Retrieved value, such as CloseFunc.
@@ -146,7 +154,10 @@ func NewRetrievedFromYAML(yamlBytes []byte, opts ...RetrievedOption) (*Retrieved
146154
if err := yaml.Unmarshal(yamlBytes, &rawConf); err != nil {
147155
// If the string is not valid YAML, we try to use it verbatim as a string.
148156
strRep := string(yamlBytes)
149-
return NewRetrieved(strRep, append(opts, withStringRepresentation(strRep))...)
157+
return NewRetrieved(strRep, append(opts,
158+
withStringRepresentation(strRep),
159+
withErrorHint(fmt.Errorf("assuming string type since contents are not valid YAML: %w", err)),
160+
)...)
150161
}
151162

152163
switch rawConf.(type) {
@@ -175,6 +186,7 @@ func NewRetrieved(rawConf any, opts ...RetrievedOption) (*Retrieved, error) {
175186
}
176187
return &Retrieved{
177188
rawConf: rawConf,
189+
errorHint: set.errorHint,
178190
closeFunc: set.closeFunc,
179191
stringRepresentation: set.stringRepresentation,
180192
isSetString: set.isSetString,
@@ -188,6 +200,9 @@ func (r *Retrieved) AsConf() (*Conf, error) {
188200
}
189201
val, ok := r.rawConf.(map[string]any)
190202
if !ok {
203+
if r.errorHint != nil {
204+
return nil, fmt.Errorf("retrieved value (type=%T) cannot be used as a Conf: %w", r.rawConf, r.errorHint)
205+
}
191206
return nil, fmt.Errorf("retrieved value (type=%T) cannot be used as a Conf", r.rawConf)
192207
}
193208
return NewFromStringMap(val), nil

0 commit comments

Comments
 (0)