hashicorp / go-multierror

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

Feature request: ability to set default formatter #62

Open ryanmcnamara opened 2 years ago

ryanmcnamara commented 2 years ago

Hi, thanks for maintaining this library

I'd like to use this library to return errors to a caller that would prefer no newlines if possible (in the event of one error). That is doable and looks like this:

func Foo() error {
    var retErr *multierror.Error
    for _, x := range getSlice() {
        if err := bar(x); err != nil {
            retErr = multierror.Append(retErr, err)
        }
    }
    return decorateFormat(retErr.ErrorOrNil())
}

func decorateFormat(err *multierror.Error) *multierror.Error {
    if err != nil {
        err.ErrorFormat = multierror.ErrorFormatFunc(func(errs []error) string {
            if len(errs) == 1 {
                return errs[0].Error()
            }
            return multierror.ListFormatFunc(errs)
        })
    }
    return err
}

Which is fine, but requires me to remember to set the listFormatFunc, I'm doing that in a separate "decorator" func because I will need to do this many times.

I would like to make it possible to specify the "default" error func so I don't have to remember to set it. This way, whenever a new multierror.Error was created, it would automatically have the format function I want. Would you accept a change like that? If so, perhaps a default global (defaults to the current ListFormatFunc) is the way to go, but would defer to you. Thanks in advance!

dolmen commented 5 months ago

Your decorateFormat func should return error in its signature instead of *multierror.Error to avoid returning (*multierror.Error)(nil) from Foo.