hashicorp / go-multierror

A Go (golang) package for representing a list of errors as a single error.
Mozilla Public License 2.0
2.28k stars 123 forks source link

Can panic-recover handling add to the function Group.Go()? #83

Open guodongq opened 11 months ago

guodongq commented 11 months ago

When the program is processed in multiple goroutines, panic may occur, which will cause main goroutine to crash directly. Can following logic add to Group.Go() ?

// Go calls the given function in a new goroutine.
//
// If the function returns an error it is added to the group multierror which
// is returned by Wait.
func (g *Group) Go(f func() error) {
    g.wg.Add(1)

    go func() {
        defer g.wg.Done()

+       defer func() {
+           if r := recover(); r != nil {
+               g.mutex.Lock()
+               g.err = Append(g.err, fmt.Errorf("%v", r))
+               g.mutex.Unlock()
+           }
+       }()

        if err := f(); err != nil {
            g.mutex.Lock()
            g.err = Append(g.err, err)
            g.mutex.Unlock()
        }
    }()
}
dolmen commented 5 months ago

@guodongq You might be interested in my module github.com/dolmen-go/rendezvous that has this feature.