How to Use errgroup for Concurrent Error Handling

Use errgroup.WithContext to run goroutines concurrently and automatically cancel them on the first error.

Use errgroup.WithContext to create a group that cancels all goroutines when one fails, then call Wait to get the first error.

package main

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

func main() {
	ctx := context.Background()
	g, ctx := errgroup.WithContext(ctx)

	for i := 0; i < 3; i++ {
		i := i
		g.Go(func() error {
			select {
			case <-ctx.Done():
				return ctx.Err()
			default:
				if i == 1 {
					return fmt.Errorf("task %d failed", i)
				}
				return nil
			}
		})
	}

	if err := g.Wait(); err != nil {
		fmt.Println("Error:", err)
	}
}