Sobes.tech
Junior — Middle

Can you share an example of how you implemented error handling using error.Group in your projects?

sobes.tech AI

Answer from AI

The errors package with the Group type (for example, from golang.org/x/sync/errgroup) allows convenient collection and handling of multiple errors that occur in parallel goroutines.

Example of using errgroup.Group for parallel task execution with error handling:

import (
    "fmt"
    "golang.org/x/sync/errgroup"
)

func processTasks() error {
    var g errgroup.Group

    tasks := []func() error{
        func() error { /* task 1 */ return nil },
        func() error { /* task 2 */ return fmt.Errorf("error in task 2") },
        func() error { /* task 3 */ return nil },
    }

    for _, task := range tasks {
        t := task
        g.Go(func() error {
            return t()
        })
    }

    if err := g.Wait(); err != nil {
        // handle the first encountered error
        return err
    }
    return nil
}

In my projects, I used errgroup to run several independent operations in parallel and to collect errors neatly, which simplifies code and improves readability.

Can you share an example of how you implemented error… - sobes.tech