zoukankan      html  css  js  c++  java
  • 10.7 Propagating errors with errgroup

    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里函数返回错误,内部实施取消语境等可运行的任务。
    
  • 相关阅读:
    若干代码坏味及解法
    编程漫谈(十八):编程三境界
    如何不虚度光阴
    打印预览内嵌浏览器的两种方法
    LODOP多个表格带表格页脚关联
    Akka学习笔记
    Spring和Springboot相关知识点整理
    python接口测试:在一个用例文件中调用另一个用例文件中定义的方法
    使用jmeter对字符串进行加密
    (八十九)c#Winform自定义控件-自定义滚动条(treeview、panel、datagridview、listbox、listview、textbox)
  • 原文地址:https://www.cnblogs.com/zrdpy/p/8655094.html
Copyright © 2011-2022 走看看