fix to return combined multiple errors
closes https://github.com/deepmap/oapi-codegen/issues/1515
MarshalJSON returns combined json marshal errors in AdditionalProperties.
e.g.
Before
error marshaling 'unsupportedType1': json: unsupported type: chan int
↓
After
error marshaling 'unsupportedType1': json: unsupported type: chan int 'unsupportedType2': json: unsupported type: func()
(requierd go 1.20)
Thanks for this!
I was wondering if maybe instead of this, we have i.e.
var errs []error for fieldName, field := range a.AdditionalProperties { object[fieldName], err := json.Marshal(field) if err != nil { errs = append(errs, fmt.Errorf("'%s': %w", fieldName, err)) } } err := errors.Join(errs...) if err != nil { return nil, fmt.Errorf("error marshaling %w", joinedError) }Which then uses
errors.Joinin a slightly easier way?
It looks to me like this is doing something similar to the internal code of errors.Join 🤔
Yep, but with an array rather than joining in the loop will probably be a little more efficient, and only does the joining once
That's right. 🚀 https://github.com/deepmap/oapi-codegen/pull/1598/commits/52f6cdc8be554cfd98baaa71c7deb16e475fa301
I think the same behavior can be achieved as follows:
var errs error
for fieldName, field := range a.AdditionalProperties {
object[fieldName], err = json.Marshal(field)
if err != nil {
errs = errors.Join(errs, fmt.Errorf("json marshal %q: %w", fieldName, err))
}
}
if errs != nil {
return nil, errs
}