r/golang•
ruibranco

Patterns that made my Go error handling less painful

discussion

After a few years of writing Go in production, I've settled on a handful of error handling patterns that have significantly reduced the "if err != nil" fatigue while keeping things idiomatic. Sharing in case it helps others.

1. Named return errors with defer for cleanup

Instead of checking error at every step in functions that acquire resources:

func processFile(path string) (err error) {
    f, err := os.Open(path)
    if err != nil {
        return fmt.Errorf("open: %w", err)
    }
    defer f.Close()
    // ... rest of function
}

This is basic, but combining named returns with defer for cleanup logic (closing connections, rolling back transactions) keeps the happy path readable.

2. Wrapping errors with context at every layer

Always wrap with %w and add the context of what YOU were trying to do, not what failed:

// Bad: just bubbles up the raw error
return err

// Better: adds context about the operation
return fmt.Errorf("fetching user %d: %w", userID, err)

When something breaks in production at 3am, the error chain tells you exactly what call path led there.

3. Sentinel errors for control flow, wrapped errors for debugging

Define package-level sentinel errors for cases where callers need to branch on the error type:

var ErrNotFound = errors.New("not found")

// In the function:
return fmt.Errorf("user %d: %w", id, ErrNotFound)

// Caller can still check:
if errors.Is(err, ErrNotFound) { ... }

4. Early returns over nested ifs

This is more style than pattern, but it transformed my readability:

// Instead of deeply nested error checks
// Return early on each error and keep the happy path at the left margin

5. Error groups for concurrent operations

errgroup.Group from golang.org/x/sync is a game changer for fan-out patterns. Collects the first error from any goroutine and cancels the rest via context.

What patterns have you all settled on? Curious if anyone's found good approaches for reducing the verbosity without losing the explicitness that makes Go errors valuable.

Posted Mar 6, 2026, 4:02 AM UTC

031
Loading comments…