Skip to content

errors: unwrap joinError to avoid deeply-nested joins #65360

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 22 additions & 13 deletions src/errors/join.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,33 @@ import (
//
// A non-nil error returned by Join implements the Unwrap() []error method.
func Join(errs ...error) error {
n := 0
for _, err := range errs {
if err != nil {
n++
allErrs := make([]error, 0, len(errs))
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This might be one of those situations where optimizing for the common use case makes sense. Given "most" error joining is of the form merr = errors.Join(merr, err), we can optimize for the single-entry error:

switch len(errs) {
  case 0:
    return nil
  case 1:
    return errs[0]
  case 2:
    if errs[0] == nil {
      return errs[1]
    } else if errs[1] == nil {
      return errs[0]
    } else {
      return &joinError{
        errs: errs, 
      }
    }
  default:
    // as below
}

for _, e := range errs {
// Ignore nil errors.
if e == nil {
continue
}

// Specifically handle nested join errors from the standard library. This
// avoids deeply-nesting values which can be unexpected when unwrapping
// errors.
joinErr, ok := e.(*joinError)
if !ok {
allErrs = append(allErrs, e)
continue
}

allErrs = append(allErrs, joinErr.errs...)
}
if n == 0 {

// Ensure we return nil if all contained errors were nil.
if len(allErrs) == 0 {
return nil
}
e := &joinError{
errs: make([]error, 0, n),
}
for _, err := range errs {
if err != nil {
e.errs = append(e.errs, err)
}

return &joinError{
errs: allErrs,
}
return e
}

type joinError struct {
Expand Down
3 changes: 3 additions & 0 deletions src/errors/join_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ func TestJoin(t *testing.T) {
}, {
errs: []error{err1, nil, err2},
want: []error{err1, err2},
}, {
errs: []error{errors.Join(err1, err2), err1, err2},
want: []error{err1, err2, err1, err2},
}} {
got := errors.Join(test.errs...).(interface{ Unwrap() []error }).Unwrap()
if !reflect.DeepEqual(got, test.want) {
Expand Down