Skip to content

Commit 62ef034

Browse files
committed
add recover in Go()
2 parents 036812b + 624b35f commit 62ef034

File tree

2 files changed

+31
-9
lines changed

2 files changed

+31
-9
lines changed

errgroup/errgroup.go

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ package errgroup
88

99
import (
1010
"context"
11+
"fmt"
1112
"sync"
1213
)
1314

@@ -51,16 +52,23 @@ func (g *Group) Wait() error {
5152
func (g *Group) Go(f func() error) {
5253
g.wg.Add(1)
5354

55+
var err error
5456
go func() {
55-
defer g.wg.Done()
57+
defer func() {
58+
if e := recover(); e != nil {
59+
err = fmt.Errorf("errgroup: recover from %+v", e)
60+
}
5661

57-
if err := f(); err != nil {
58-
g.errOnce.Do(func() {
59-
g.err = err
60-
if g.cancel != nil {
61-
g.cancel()
62-
}
63-
})
64-
}
62+
if err != nil {
63+
g.errOnce.Do(func() {
64+
g.err = err
65+
if g.cancel != nil {
66+
g.cancel()
67+
}
68+
})
69+
}
70+
g.wg.Done()
71+
}()
72+
err = f()
6573
}()
6674
}

errgroup/errgroup_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,3 +174,17 @@ func TestWithContext(t *testing.T) {
174174
}
175175
}
176176
}
177+
178+
func TestGroup_panic(t *testing.T) {
179+
g, _ := errgroup.WithContext(context.Background())
180+
181+
g.Go(func() error {
182+
panic("Ops!!!")
183+
})
184+
185+
if err := g.Wait(); err == nil {
186+
t.Errorf("after %T.Go(func() error { panic(\"Ops!!!\") })\n"+
187+
"g.Wait() = %v; want %v",
188+
g, err, "a non-nil error")
189+
}
190+
}

0 commit comments

Comments
 (0)