Skip to content

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

@maxiride

Description

@maxiride

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions