hashicorp / go-multierror

A Go (golang) package for representing a list of errors as a single error.
Mozilla Public License 2.0
2.3k stars 123 forks source link

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

Open maxiride opened 3 years ago

maxiride commented 3 years ago

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