Go Goroutine Err Group
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.
Right
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
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[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
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