Skip to content

errors: clarify that Join doesn't extend already-joined errors #60215

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
5 changes: 5 additions & 0 deletions src/errors/join.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ package errors
// between each string.
//
// A non-nil error returned by Join implements the Unwrap() []error method.
//
// Calling Join on an error that was previously returned by Join wraps
// the error again. Consequently, calling Unwrap() []error on the result
// of Join(Join(err1, err2), err3) returns a slice with 2 items, of which
// the first one implements Unwrap() []error too.
func Join(errs ...error) error {
n := 0
for _, err := range errs {
Expand Down
45 changes: 45 additions & 0 deletions src/errors/join_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,48 @@ func TestJoinErrorMethod(t *testing.T) {
}
}
}

func TestJoinWithJoinedError(t *testing.T) {
err1 := errors.New("err1")
err2 := errors.New("err2")

var err error
err = errors.Join(err, err1)
if err == nil {
t.Fatal("errors.Join(err, err1) = nil, want non-nil")
}

gotErrs := err.(interface{ Unwrap() []error }).Unwrap()
if len(gotErrs) != 1 {
t.Fatalf("errors.Join(err, err1) returns errors with len=%v, want len==1", len(gotErrs))
}

err = errors.Join(err, err2)
if err == nil {
t.Fatal("errors.Join(err, err2) = nil, want non-nil")
}

gotErrs = err.(interface{ Unwrap() []error }).Unwrap()
if len(gotErrs) != 2 {
t.Fatalf("errors.Join(err, err2) returns errors with len=%v, want len==2", len(gotErrs))
}

// Wraps the error again, so the resulting joined error will have len==1
err = errors.Join(err, nil)
if err == nil {
t.Fatal("errors.Join(err, nil) = nil, want non-nil")
}

gotErrs = err.(interface{ Unwrap() []error }).Unwrap()
if len(gotErrs) != 1 {
t.Fatalf("errors.Join(err, nil) returns errors with len=%v, want len==1", len(gotErrs))
}

if err.Error() != "err1\nerr2" {
t.Errorf("Join(err, nil).Error() = %q; want %q", err.Error(), "err1\nerr2")
}

if _, ok := gotErrs[0].(interface{ Unwrap() []error }); !ok {
t.Error("first error returned by errors.Join(err, nil) is not a joined error")
}
}