GO

Go Error Handling

Idiomatic Go error handling with explicit error returns

Details

Language / Topic
goGo
Category
Error Handling

Rules

balanced
- Always check returned errors immediately with `if err != nil` — never discard errors with `_`.
- Use `fmt.Errorf("context: %w", err)` to wrap errors with context while preserving the error chain.
- Use sentinel errors (`var ErrNotFound = errors.New("not found")`) for expected error conditions that callers check with `errors.Is`.
- Return `(value, error)` pairs from functions — never use panics for expected error conditions.
- Use `errors.Is(err, target)` to check for specific errors in the chain, not `err == target`.
- Use `errors.As(err, &target)` to extract typed errors from wrapped chains.
- Create custom error types implementing the `error` interface for errors that carry structured data (status codes, fields).
- Use `defer` for cleanup in error paths — ensures resources are released even when returning early.
- Wrap errors at each layer boundary with additional context: `fmt.Errorf("repository.GetUser: %w", err)`.