Skip to content

Go Goroutine Err Group

DodaTech 1 min read

In this tutorial, you'll learn about Go Goroutine: Error Handling with errgroup. We cover key concepts, practical examples, and best practices.

Error groups -- Use golang.org/x/sync/errgroup to manage goroutine errors and cancellation.

The Problem

sync.WaitGroup doesn't propagate errors. errgroup extends WaitGroup with error propagation and automatic context cancellation on first error.

Wrong

var wg sync.WaitGroup
for _, task := range tasks {
    wg.Add(1)
    go func(t Task) {
        defer wg.Done()
        if err := t.Process(); err != nil {
            // Error ignored!
        }
    }(task)
}
wg.Wait()

Output:

// Errors silently ignored. No cancellation on failure.
g, ctx := errgroup.WithContext(ctx)
for _, task := range tasks {
    task := task
    g.Go(func() error {
        return task.Process(ctx)
    })
}
if err := g.Wait(); err != nil {
    log.Fatal("Task failed:", err)
}

Output:

// All tasks complete or one fails causing cancellation
// Error propagated on first failure

Prevention

  • Use errgroup for goroutines that return errors
  • WithContext creates a cancellable context
  • First error cancels the context for other goroutines
  • g.Wait() returns the first error (or nil)
  • Limit concurrency with errgroup's SetLimit

Common Mistakes with goroutine err group

  1. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  2. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  3. Misunderstanding that String is [Char] with poor performance for large text operations

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**Does errgroup use context?**

Yes. g, ctx := errgroup.WithContext(ctx) returns cancellable context.

How to limit concurrency?

g.SetLimit(10) limits the number of active goroutines.

What happens on first error?

Context is cancelled. Other goroutines should check ctx.Done().


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro