-
Notifications
You must be signed in to change notification settings - Fork 0
/
group.go
38 lines (33 loc) · 937 Bytes
/
group.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package relax
import (
"context"
"golang.org/x/sync/errgroup"
)
// RoutineGroup is a wrapper around golang.org/x/sync/errgroup.Group that
// recovers from panics and returns them as errors
type RoutineGroup struct {
*errgroup.Group
}
// NewGroup instantiates an RoutineGroup and corresponding context.
// This function should be used the same way as errgroup.WithContext() from
// golang.org/x/sync/errgroup
func NewGroup(ctx context.Context) (*RoutineGroup, context.Context) {
errgroup, groupCtx := errgroup.WithContext(ctx)
return &RoutineGroup{
Group: errgroup,
}, groupCtx
}
// Go runs a provided func in a goroutine while ensuring that
// any panic is recovered and returned as an error
func (rg *RoutineGroup) Go(f func() error) {
rg.Group.Go(func() (err error) {
// Handle panics
defer func() {
if r := recover(); r != nil {
err = recoverError(r)
}
}()
// Call the provided func
return f()
})
}