Home>Articles

This chapter is from the book

This chapter is from the book

Error Management with Error Groups

One of the downsides of thesync.WaitGroupis that it has no error management built in to capture errors that occur in the goroutines. It also has an API that requires exact implementation; otherwise, it panics.

To help address some of these issues, thegolang.org/x/sync/errgroup,10Listing 13.15, package was introduced, providing a simpler API as well as built-in error management.

Listing 13.15 Thegolang.org/x/sync/errgroupPackage
$ go doc golang.org/x/sync/errgroup package errgroup // import "golang.org/x/sync/errgroup" Package errgroup provides synchronization, error propagation, and Contextarrow.jpgcancelation for groups of goroutines working on subtasks of a common task. type Group struct{ ... } func WithContext(ctx context.Context) (*Group, context.Context)

Go Version: go1.19

The Problem

Consider Listing 13.16. In the example, a number of goroutines are launched to call thegenerateThumbnailfunctions. Async.WaitGroupis used to wait for all the goroutines to finish.

Listing 13.16 Managing Goroutines withsync.WaitGroup
funcTest_ThumbnailGenerator(t*testing.T) {t.Parallel()// image that we need thumbnails forconstimage="foo.png"varwg sync.WaitGroup// start 5 goroutines to generate thumbnailsfori:=0;i<5;i++ {wg.Add(1)// start a new goroutine for each thumbnailgogenerateThumbnail(&wg,image,i+1)}fmt.打印ln("Waiting for thumbnails to be generated")// wait for all goroutines to finishwg.Wait()fmt.打印ln("Finished generate all thumbnails") }

Inside thegenerateThumbnailfunction, Listing 13.17, we see that there is an error that occurs if thesizeargument is divisible by 5, which causes a panic, and the application crashes.

Listing 13.17 ThegenerateThumbnailFunction
funcgenerateThumbnail(wg*sync.WaitGroup,imagestring,sizeint) {deferwg.Done()// error if the size is divisible by 5ifsize%5==0{// how do we return this error back to the main // goroutine without panicking?err:=fmt.Errorf("%d is divisible by 5",size)panic(err) }// thumbnail to be generatedthumb:=fmt.Sprintf("%s@%dx.png",image,size)fmt.打印ln("Generating thumbnail:",thumb)// wait for the thumbnail to be readytime.Sleep(time.Millisecond*time.Duration(size))fmt.打印ln("Finished generating thumbnail:",thumb) }

$ go test -v === RUN Test_ThumbnailGenerator === PAUSE Test_ThumbnailGenerator === CONT Test_ThumbnailGenerator Waiting for thumbnails to be generated panic: 5 is divisible by 5 goroutine 9 [running]: demo.generateThumbnail(0x0?, {0x10268ac77?, 0x0?}, 0x0?) ./demo_test.go:47 +0x21c created by demo.Test_ThumbnailGenerator ./demo_test.go:24 +0x4c exit status 2 FAIL demo 0.619s

Go Version: go1.19

The Error Group

Theerrgroup.Group11type provides a minimal API when compared to thesync.WaitGrouptype. There are only two methods:errgroup.Group.Go12anderrgroup.Group.Wait.13

Theerrgroup.Grouptype, Listing 13.18, manages the counter for you, so there is no need for counter management as there is with thesync.WaitGrouptype.

Listing 13.18 Theerrgroup.GroupType
$ go doc golang.org/x/sync/errgroup.Group package errgroup // import "golang.org/x/sync/errgroup" type Group struct { // Has unexported fields. } A Group is a collection of goroutines working on subtasks that are partarrow.jpgof the same overall task. A zero Group is valid and does not cancel on error. func WithContext(ctx context.Context) (*Group, context.Context) func (g *Group) Go(f func() error) func (g *Group) Wait() error

Go Version: go1.19

TheGoMethod

You use theerrgroup.Group.Gomethod, Listing 13.19, to launch a goroutine for the providedfunc() errorfunction provided. Thefunc() errorfunction is executed in a goroutine. If the function returns an error, theerrgroup.Grouptype captures the error, cancels the other goroutines, and returns the error to the caller from theerrgroup.Group.Waitmethod.

Listing 13.19 Theerrgroup.Group.GoMethod
$ go doc golang.org/x/sync/errgroup.Group.Go package errgroup // import "golang.org/x/sync/errgroup" func (g *Group) Go(f func() error) Go calls the given function in a new goroutine. The first call to return a non-nil error cancels the group; its errorarrow.jpgwill be returned by Wait.

Go Version: go1.19

TheWaitMethod

You useerrgroup.Group.Waitmethod, Listing 13.20, to wait for all the goroutines to finish. If any of the goroutines return an error, theerrgroup.Grouptype returns the error to the caller.

Listing 13.20 Theerrgroup.Group.WaitMethod
$ go doc golang.org/x/sync/errgroup.Group.Wait package errgroup // import "golang.org/x/sync/errgroup" func (g *Group) Wait() error Wait blocks until all function calls from the Go method have returned,arrow.jpgthen returns the first non-nil error (if any) from them.

Go Version: go1.19

It is important to understand theerrgroup.Group.Waitmethod returnsonlythefirsterror that occurs. Any other errors that occur are ignored. In Listing 13.21, we are calling theGomethod on anerrorgroup.Group10 times. Each time we pass a function that sleeps for a random time, prints a messages, and then returns an error. From the output of the test, you can see that the error returned by theWaitmethod was returned from function number 4. The other nine errors are discarded.

Listing 13.21 Theerrgroup.Group.WaitMethod Returns Only the First Error
funcTest_ErrorGroup_Multiple_Errors(t*testing.T) {t.Parallel()varwg errgroup.Groupfori:=0;i<10;i++ {i:=i+1wg.Go(func()error{time.Sleep(time.Millisecond*time.Duration(rand.Intn(10)))fmt.打印f("about to error from %d\n",i)returnfmt.Errorf("error %d",i)}) }err:=wg.Wait()iferr!={t.Fatal(err) }}

$ go test -v === RUN Test_ErrorGroup_Multiple_Errors === PAUSE Test_ErrorGroup_Multiple_Errors === CONT Test_ErrorGroup_Multiple_Errors about to error from 4 about to error from 6 about to error from 3 about to error from 1 about to error from 9 about to error from 10 about to error from 8 about to error from 5 about to error from 2 about to error from 7 demo_test.go:38: error 4 --- FAIL: Test_ErrorGroup_Multiple_Errors (0.01s) FAIL exit status 1 FAIL demo 0.263s

Go Version: go1.19

Listening for Error Group Cancellation

When launching a number of goroutines, it can often be useful to let others know the tasks have all completed. Theerrgroup.WithContext14function, Listing 13.22, returns a newerrgroup.Group, as well as acontext.Contextthat can be listened to for cancellation.

Listing 13.22 Theerrgroup.WithContextFunction
funcTest_ErrorGroup_Context(t*testing.T) {t.Parallel()// create a new error group // and a context that will be canceled // when the group is donewg,ctx:=errgroup.WithContext(context.Background())// create a quit channel for the goroutine // waiting for the context to be canceled // can close to signal the goroutine has finishedquit:=make(陈结构{})// launch a goroutine that will // wait for the errgroup context to finishgo func() {fmt.打印ln("waiting for context to cancel")// wait for the context to be canceled<-ctx.Done()fmt.打印ln("context canceled")// close the quit channel so the test // will finishclose(quit)}()// add a task to the errgroupwg.Go(func()error{time.Sleep(time.Millisecond*5)return})// wait for the errgroup to finisherr:=wg.Wait()iferr!={t.Fatal(err) }// wait for the context goroutine to finish<-quit}

$ go test -v === RUN Test_ErrorGroup_Context === PAUSE Test_ErrorGroup_Context === CONT Test_ErrorGroup_Context waiting for context to cancel context canceled --- PASS: Test_ErrorGroup_Context (0.01s) PASS ok demo 0.725s

Go Version: go1.19

Wrapping Up Error Groups

Theerrgroup.Grouptype provides a simpler API than thesync.WaitGrouptype. It also provides built-in error management. This makes managing goroutines with error handling much easier. The downside is that it is not as flexible as thesync.WaitGrouptype, where you are in charge of managing the counter.

Which type you choose to use will vary from situation to situation, so it is important to understand the tradeoffs and benefits of each before deciding which type to use.

Using aerrgroup.Groupallows you to clean up your code significantly to make it easier to understand and to manage errors.

As you can see from Listing 13.23, thegenerateThumbnailfunction no longer needs to take async.WaitGroupas an argument.

Listing 13.23 Update thegenerateThumbnailFunction to useerrgroup.Group
funcgenerateThumbnail(imagestring,sizeint)error{// error if the size is divisible by 5ifsize%5==0{returnfmt.Errorf("%d is divisible by 5",size) }// thumbnail to be generatedthumb:=fmt.Sprintf("%s@%dx.png",image,size)fmt.打印ln("Generating thumbnail:",thumb)// wait for the thumbnail to be readytime.Sleep(time.Millisecond*time.Duration(size))fmt.打印ln("Finished generating thumbnail:",thumb)return}

Being able to return an error from the function means the function no longer needs to panic.

As you can see from the output, Listing 13.24, thegenerateThumbnailfunction no longer panics, and the test is now able to exit properly.

Listing 13.24 Using theerrgroup.GroupType
funcTest_ThumbnailGenerator(t*testing.T) {t.Parallel()// image that we need thumbnails forconstimage="foo.png"// create a new error groupvarwg errgroup.Group// start 5 goroutines to generate thumbnailsfori:=0;i<5;i++ {// capture the i to the current scopei:=i// start a new goroutine for each thumbnailwg.Go(func()error{/ /返回generateThumbn的结果ailreturngenerateThumbnail(image,i) })}fmt.打印ln("Waiting for thumbnails to be generated")// wait for all goroutines to finisherr:=wg.Wait()// check for any errorsiferr!={t.Fatal(err) }fmt.打印ln("Finished generate all thumbnails") }

$ go test -v === RUN Test_ThumbnailGenerator === PAUSE Test_ThumbnailGenerator === CONT Test_ThumbnailGenerator Waiting for thumbnails to be generated Generating thumbnail: foo.png@4x.png Generating thumbnail: foo.png@3x.png Generating thumbnail: foo.png@1x.png Generating thumbnail: foo.png@2x.png Finished generating thumbnail: foo.png@1x.png Finished generating thumbnail: foo.png@2x.png Finished generating thumbnail: foo.png@3x.png Finished generating thumbnail: foo.png@4x.png demo_test.go:43: 0 is divisible by 5 --- FAIL: Test_ThumbnailGenerator (0.00s) FAIL exit status 1 FAIL demo 0.570s

Go Version: go1.19

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

时事通讯

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simplyemailinformation@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through ourContact Us form.

Other Collection and Use of Information


Application and System Logs

皮尔森自动收集日志数据来帮助sure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on theAccount page. If a user no longer desires our service and desires to delete his or her account, please contact us atcustomer-service@informit.comand we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive:www.e-skidka.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information toNevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read ourSupplemental privacy statement for California residentsin conjunction with this Privacy Notice. TheSupplemental privacy statement for California residentsexplains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • 个人的同意(或他们的括弧t, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Pleasecontact usabout this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


我们可以重新vise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020