Gogoerror-handlingwrappingbest-practicesproduction-ready

Error Wrapping and Context

Idiomatic Go error wrapping patterns that add context at each layer while preserving the ability to inspect the original error.


title: "Error Wrapping and Context" description: "Idiomatic Go error wrapping patterns that add context at each layer while preserving the ability to inspect the original error." category: "Go" language: "go" tags: ["go", "error-handling", "wrapping", "best-practices", "production-ready"] createdAt: "2025-04-05" updatedAt: "2025-04-20"

Overview

Idiomatic Go error handling where each layer adds context via fmt.Errorf("%w", err) while preserving the ability to inspect root causes with errors.Is(). The handler layer maps domain errors to HTTP responses without leaking implementation details.

Code

// Repository wraps with context
return nil, fmt.Errorf("FindByID(%s): %w", id, ErrUserNotFound)
 
// Handler inspects domain errors
if errors.Is(err, ErrUserNotFound) {
    w.WriteHeader(http.StatusNotFound)
}

Notes

  • %w verb creates an error chain that errors.Is() and errors.As() can traverse
  • Define domain errors as package-level var declarations (sentinel errors)
  • Each layer adds just enough context to trace the error path without redundancy
  • Never expose raw internal errors to API clients (security and UX concern)
  • Use errors.Join() (Go 1.20+) for wrapping multiple errors simultaneously