1 回答
TA贡献1802条经验 获得超4个赞
使用golang.org/x/sync/errgroup等待并处理来自 goroutine 的错误。
package main
import (
"errors"
"log"
"sync"
"golang.org/x/sync/errgroup"
)
func main() {
c := make(chan int, 10)
var g errgroup.Group
g.Go(func() error {
return doSomething(c)
})
// g.Wait waits for all goroutines to complete
// and returns the first non-nil error returned
// by one of the goroutines.
if err := g.Wait(); err != nil {
log.Fatal(err)
}
}
func doSomething(c chan int) error {
defer close(c)
for i := 0; i < 10; i++ {
n, err := someFunctionThatCanError()
if err != nil {
return err
}
c <- n
}
return nil
}
func someFunctionThatCanError() (int, error) {
return 1, errors.New("an error")
}
- 1 回答
- 0 关注
- 124 浏览
添加回答
举报