Skip to content
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

Add recover protection to Go method #12

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
26 changes: 17 additions & 9 deletions errgroup/errgroup.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ package errgroup

import (
"context"
"fmt"
"sync"
)

Expand Down Expand Up @@ -51,16 +52,23 @@ func (g *Group) Wait() error {
func (g *Group) Go(f func() error) {
g.wg.Add(1)

var err error
go func() {
defer g.wg.Done()
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("errgroup: recover from %+v", e)
}

if err := f(); err != nil {
g.errOnce.Do(func() {
g.err = err
if g.cancel != nil {
g.cancel()
}
})
}
if err != nil {
g.errOnce.Do(func() {
g.err = err
if g.cancel != nil {
g.cancel()
}
})
}
g.wg.Done()
}()
err = f()
}()
}
14 changes: 14 additions & 0 deletions errgroup/errgroup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,3 +174,17 @@ func TestWithContext(t *testing.T) {
}
}
}

func TestGroup_panic(t *testing.T) {
g, _ := errgroup.WithContext(context.Background())

g.Go(func() error {
panic("Ops!!!")
})

if err := g.Wait(); err == nil {
t.Errorf("after %T.Go(func() error { panic(\"Ops!!!\") })\n"+
"g.Wait() = %v; want %v",
g, err, "a non-nil error")
}
}