DEV Community

Young Gao
Young Gao

Posted on

Pragmatic Error Handling in Go

Pragmatic Error Handling in Go

Beyond if err != nil - techniques that work.

Always Wrap

return fmt.Errorf("get order %s: %w", id, err)
Enter fullscreen mode Exit fullscreen mode

Sentinels

var ErrNotFound = errors.New("not found")
Enter fullscreen mode Exit fullscreen mode

HTTP Pattern

type HandlerFunc func(w http.ResponseWriter, r *http.Request) error
Enter fullscreen mode Exit fullscreen mode

errgroup

g, ctx := errgroup.WithContext(ctx)
g.Go(func() error { return fn() })
Enter fullscreen mode Exit fullscreen mode

If this was helpful, you can support my work at ko-fi.com/nopkt


If this article helped you, consider buying me a coffee on Ko-fi! Follow me for more production backend patterns.

Top comments (0)