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

Convenience Join function for array of errors #55

Closed aweis89 closed 2 years ago

aweis89 commented 2 years ago

When we have an array of errors we want to combine into a single one, we need to do the following:

func Errs() error {
    errs := []errors{}
    ...
    if len(errs) > 1 {
        return multierror.Append(keyErrs[0], keyErrs[1:]...)
    }
    return errs[0]
}

Or we can create a loop to build:

func Errs() (errs error) {
    builtErrs := []errors{}
    ...
    for _, err := range builtErrs {
        errs = multierror.Append(errs, err)
    }
    return errs
}

Instead of having to check length or use ranges, might be nice to have a Join function that takes an array of errors regardless of size:

func Errs() error {
    errs := []errors{}
    ...
    return multierror.Join(errs)
}

Notably I came across this issue in a situation where I need to know the number errors before returning, hence I need to use an error slice when initially building the errors rather than use Append directly.