Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Len() with nil multierror should return 0 instead of panic #54

Open
maxiride opened this issue Sep 13, 2021 · 0 comments
Open

Len() with nil multierror should return 0 instead of panic #54

maxiride opened this issue Sep 13, 2021 · 0 comments

Comments

@maxiride
Copy link

maxiride commented Sep 13, 2021

As of now the method can be called only on a not nil Error.

I stumbled upon the situation where I wanted handle how many errors a multierror variable contained, however Len can't be called on a nil multierror (which would cause a runtime panic).

This implies that a nil multierror and zero length multierror are treated differently. I would expect the example in the playground to return 0 instead of throwing a panic. Is this an intentional design choice or maybe there is room for improvement?

https://play.golang.org/p/n7fwsjBybhs

The Len() method could be changed as the following without breaking changes (I think):

func (err *Error) Len() int {
	if err != nil {
		return len(err.Errors)
	}

	return 0
}

Otherwise one would need to go through the ErrOrNil method with little, although not needed, overhead.

         var merr *multierror.Error
	if merr.ErrOrNil != nil {
		fmt.Println(merr.Len())
	} else {
		fmt.Println("0")
	}

I should also add that his condition happens when a multierror is initialized but nothing has been appended to it, in fact appending nil errors correctly fills it with zeroes.
https://play.golang.org/p/B3P_aNnms2W

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant