oapi-codegen icon indicating copy to clipboard operation
oapi-codegen copied to clipboard

fix to return combined multiple errors

Open eyasy1217 opened this issue 1 year ago • 4 comments

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)

eyasy1217 avatar May 06 '24 04:05 eyasy1217

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.Join in a slightly easier way?

It looks to me like this is doing something similar to the internal code of errors.Join 🤔

eyasy1217 avatar May 06 '24 10:05 eyasy1217

Yep, but with an array rather than joining in the loop will probably be a little more efficient, and only does the joining once

jamietanna avatar May 06 '24 11:05 jamietanna

That's right. 🚀 https://github.com/deepmap/oapi-codegen/pull/1598/commits/52f6cdc8be554cfd98baaa71c7deb16e475fa301

eyasy1217 avatar May 06 '24 12:05 eyasy1217

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
}

gaiaz-iusipov avatar Jun 28 '24 19:06 gaiaz-iusipov