Skip to content

In ErrorPool, store errors as []error instead of flattened error #143

Open

Description

@akallu

In the following snippet, we can see that errors are joined as they come in:

func (p *ErrorPool) addErr(err error) {
	if err != nil {
		p.mu.Lock()
		if p.onlyFirstError {
			if p.errs == nil {
				p.errs = err
			}
		} else {
			p.errs = multierror.Join(p.errs, err)
		}
		p.mu.Unlock()
	}
}

But this makes it incredibly difficult, without a recursive function, to pull the underlying errors out when consuming them from ErrorPool#Wait() (the current approach also stores the errors in a more suboptimal manner leading to more memory usage, but this isn't a huge deal):

func unwrapErrors(err error) []error {
	if err == nil {
		return nil
	}
	v, ok := err.(interface{ Unwrap() []error })
	if !ok {
		return []error{err}
	}
	var errs []error
	for _, wErr := range v.Unwrap() {
		errs = append(errs, unwrapErrors(wErr)...)
	}
	return errs
}

If the errors were kept as []error, and errors.Join(p.errs) was done inside ErrorPool#Wait(), it would be a 1-liner to pull the underlying errors out:

res, err := myPool.Wait()
errs := err.(interface{ Unwrap() []error }).Unwrap()

I don't mind doing the work for this, and it should be noted that it is backwards compatible w/ folks in the wild who have created their own functions like unwrapErrors above.

Activity

  1. changed the title [-]In errorPool, stored errors as `[]error` instead of `error`[/-] on Nov 6, 2024
  2. changed the title [-]In `ErrorPool`, stored errors as `[]error` instead of `error`[/-] on Nov 6, 2024
  3. akallu commented on Dec 19, 2024

    @akallu
    Author

    @camdencheek sorry to bother, but I saw you active in a prior issue. Any thoughts on whether I can move ahead with contributing this code? Would love to get this ironed out if possible, and thanks for creating such a great library!

  4. camdencheek commented on Dec 19, 2024

    @camdencheek
    Contributor

    Hey @akallu, sorry for the delayed reponse. This is a great suggestion -- I'd be happy to accept a contribution here 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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