Propagating errors with errgroup
This recipe will show how to easily use the errgroup extension package to detect the error within the group of goroutines that run subtasks, within a common task.
传播错误的errgroup
本章将说明如何轻松地使用errgroup扩展包检测Goroutines运行子任务的组内的错误,在一个共同的任务。
package main
import (
"bufio"
"context"
"fmt"
"log"
"strings"
"golang.org/x/sync/errgroup"
)
const data = `line one
line two with more words
error: This is erroneous line`
func main() {
log.Printf("Application %s starting.", "Error Detection")
scanner := bufio.NewScanner(strings.NewReader(data))
scanner.Split(bufio.ScanLines)
// For each line fire a goroutine
g, _ := errgroup.WithContext(context.Background())
for scanner.Scan() {
row := scanner.Text()
g.Go(func() error {
return func(s string) error {
if strings.Contains(s, "error:") {
return fmt.Errorf(s)
}
return nil
}(row)
})
}
// Wait until the goroutines finish
if err := g.Wait(); err != nil {
fmt.Println("Error while waiting: " + err.Error())
}
}
/*
Error while waiting: error: This is erroneous line
2018/03/27 01:04:01 Application Error Detection starting.
*/
The golang.org/x/sync/errgroup package helps to simplify the error propagation and cancellation by context for goroutine groups. The Group contains the Go method which consumes the no-arg function returning the error. This function should contain the task which should be done by the executed goroutine. The Wait method of the Group from errgroup waits until all executed tasks from the Go method are complete, and if any of them are returned err, then the first non-nil error is returned. This way, it is possible to simply propagate the error from the group of running goroutines.
Note that the Group is also created with the use of context. The Context serves as the mechanism to cancel other tasks, if the error occurs. After the goroutine function returns the error , the inner implementation cancels the context and so could be the running task.
的golang.org/x/sync/errgroup包有助于通过简化误差传播语境的goroutine里组和注销。该组包含go方法,该方法消耗返回错误的无精函数。这个函数应该包含哪些应该由执行的goroutine里完成任务。从errgroup本组等方法等所有执行的任务从走法是完整的,如果任何人都返回错误,那么第一个非零返回错误。这样,就有可能只是传播从运行组的错误概念。
注意,该组也是使用上下文创建的。如果发生错误,则上下文作为取消其他任务的机制。在goroutine里函数返回错误,内部实施取消语境等可运行的任务。