Home > Articles

This chapter is from the book

This chapter is from the book

Error Management with Error Groups

One of the downsides of the sync.WaitGroup is 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, the golang.org/x/sync/errgroup,10 Listing 13.15, package was introduced, providing a simpler API as well as built-in error management.

Listing 13.15 The golang.org/x/sync/errgroup Package
$ go doc golang.org/x/sync/errgroup

package errgroup // import "golang.org/x/sync/errgroup"

Package errgroup provides synchronization, error propagation, and Context
arrow.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 the generateThumbnail functions. A sync.WaitGroup is used to wait for all the goroutines to finish.

Listing 13.16 Managing Goroutines with sync.WaitGroup
func Test_ThumbnailGenerator(t *testing.T) {
    t.Parallel()

    // image that we need thumbnails for
    const image = "foo.png"

    var wg sync.WaitGroup

    // start 5 goroutines to generate thumbnails
    for i := 0; i < 5; i++ {
        wg.Add(1)

        // start a new goroutine for each thumbnail
        go generateThumbnail(&wg, image, i+1)

    }

    fmt.Println("Waiting for thumbnails to be generated")

    // wait for all goroutines to finish
    wg.Wait()

    fmt.Println("Finished generate all thumbnails")
}

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

Listing 13.17 The generateThumbnail Function
func generateThumbnail(wg *sync.WaitGroup, image string, size int) {
    defer wg.Done()

    // error if the size is divisible by 5
    if size%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 generated
    thumb := fmt.Sprintf("%s@%dx.png", image, size)

    fmt.Println("Generating thumbnail:", thumb)

    // wait for the thumbnail to be ready
    time.Sleep(time.Millisecond * time.Duration(size))

    fmt.Println("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

The errgroup.Group11 type provides a minimal API when compared to the sync.WaitGroup type. There are only two methods: errgroup.Group.Go12 and errgroup.Group.Wait.13

The errgroup.Group type, Listing 13.18, manages the counter for you, so there is no need for counter management as there is with the sync.WaitGroup type.

Listing 13.18 The errgroup.Group Type
$ 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 part
    arrow.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

The Go Method

You use the errgroup.Group.Go method, Listing 13.19, to launch a goroutine for the provided func() error function provided. The func() error function is executed in a goroutine. If the function returns an error, the errgroup.Group type captures the error, cancels the other goroutines, and returns the error to the caller from the errgroup.Group.Wait method.

Listing 13.19 The errgroup.Group.Go Method
$ 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 error
    arrow.jpgwill be returned by Wait.

Go Version: go1.19

The Wait Method

You use errgroup.Group.Wait method, Listing 13.20, to wait for all the goroutines to finish. If any of the goroutines return an error, the errgroup.Group type returns the error to the caller.

Listing 13.20 The errgroup.Group.Wait Method
$ 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 the errgroup.Group.Wait method returns only the first error that occurs. Any other errors that occur are ignored. In Listing 13.21, we are calling the Go method on an errorgroup.Group 10 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 the Wait method was returned from function number 4. The other nine errors are discarded.

Listing 13.21 The errgroup.Group.Wait Method Returns Only the First Error
func Test_ErrorGroup_Multiple_Errors(t *testing.T) {
    t.Parallel()

    var wg errgroup.Group

    for i := 0; i < 10; i++ {
        i := i + 1

        wg.Go(func() error {

            time.Sleep(time.Millisecond * time.Duration(rand.Intn(10)))

            fmt.Printf("about to error from %d\n", i)

            return fmt.Errorf("error %d", i)
        })
    }

    err := wg.Wait()
    if err != nil {
        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. The errgroup.WithContext14 function, Listing 13.22, returns a new errgroup.Group, as well as a context.Context that can be listened to for cancellation.

Listing 13.22 The errgroup.WithContext Function
func Test_ErrorGroup_Context(t *testing.T) {
    t.Parallel()

    // create a new error group
    // and a context that will be canceled
    // when the group is done
    wg, 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 finished
    quit := make(chan struct{})

    // launch a goroutine that will
    // wait for the errgroup context to finish
    go func() {
        fmt.Println("waiting for context to cancel")

        // wait for the context to be canceled
        <-ctx.Done()

        fmt.Println("context canceled")

        // close the quit channel so the test
        // will finish
        close(quit)
    }()

    // add a task to the errgroup
    wg.Go(func() error {
        time.Sleep(time.Millisecond * 5)
        return nil
    })

    // wait for the errgroup to finish
    err := wg.Wait()
    if err != nil {
        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

The errgroup.Group type provides a simpler API than the sync.WaitGroup type. 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 the sync.WaitGroup type, 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 a errgroup.Group allows 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, the generateThumbnail function no longer needs to take a sync.WaitGroup as an argument.

Listing 13.23 Update the generateThumbnail Function to use errgroup.Group
func generateThumbnail(image string, size int) error {

    // error if the size is divisible by 5
    if size%5 == 0 {
        return fmt.Errorf("%d is divisible by 5", size)
    }

    // thumbnail to be generated
    thumb := fmt.Sprintf("%s@%dx.png", image, size)

    fmt.Println("Generating thumbnail:", thumb)

    // wait for the thumbnail to be ready
    time.Sleep(time.Millisecond * time.Duration(size))

    fmt.Println("Finished generating thumbnail:", thumb)

    return nil
}

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, the generateThumbnail function no longer panics, and the test is now able to exit properly.

Listing 13.24 Using the errgroup.Group Type
func Test_ThumbnailGenerator(t *testing.T) {
    t.Parallel()

    // image that we need thumbnails for
    const image = "foo.png"

    // create a new error group
    var wg errgroup.Group

    // start 5 goroutines to generate thumbnails
    for i := 0; i < 5; i++ {

        // capture the i to the current scope
        i := i

        // start a new goroutine for each thumbnail
        wg.Go(func() error {

            // return the result of generateThumbnail
            return generateThumbnail(image, i)
        })

    }

    fmt.Println("Waiting for thumbnails to be generated")

    // wait for all goroutines to finish
    err := wg.Wait()

    // check for any errors
    if err != nil {
        t.Fatal(err)
    }

    fmt.Println("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.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@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 our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure 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 the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and 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.informit.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 to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains 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.
  • With the consent of the individual (or their parent, 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


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise 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