Error Handling
- Wrap, inspect and combine errors with
%w,errors.Is,errors.As(anderrors.AsType, Go 1.26) anderrors.Join. - Design a domain error vocabulary for payments (insufficient funds, duplicate request, unknown outcome) that callers can branch on.
- Decide where
panic/recoverbelong and where they never do. - Translate errors at service edges to HTTP status / gRPC codes, without leaking internals, and log each error exactly once.
TL;DR
- An error is any value with
Error() string. Handle it where it occurs, or return it with added context — never both log and return. - Wrap with
fmt.Errorf("load account %s: %w", id, err). Inspect witherrors.Is(identity) anderrors.As(type) — they walk the whole chain;==and type assertions do not. - Use sentinels (
ErrNotFound) for conditions callers branch on, typed errors when callers need data (available balance), and keep everything else opaque. - Translate at boundaries: the repository turns a PostgreSQL unique violation into
ErrDuplicateRequest; the HTTP layer turnsErrDuplicateRequestinto 409. Don't letpgconn.PgErrorreach the handler. panicis for programmer bugs and impossible states. Recover only at goroutine boundaries (request middleware, worker loops) — an unrecovered panic in any goroutine kills the process.- In payments, distinguish definitive failure (declined), safe to retry (rejected before sending) and unknown outcome (timeout after sending). The last one must never be blindly retried.
Why it matters
Error classification is a correctness property in money systems, not a style concern:
- A card authorization times out. Did the issuer approve it? You don't know. Retrying without an idempotency key may double-charge; reporting "failed" may lose a sale that actually went through. The error type must say "unknown outcome", and the flow must reconcile (status inquiry, then settlement files).
- A client retries
POST /transferswith the same idempotency key. The second insert hits a unique constraint. If that surfaces as a 500, the client retries forever; mapped toErrDuplicateRequest, you return the original result (see Idempotency & Exactly-Once). insufficient fundsis a normal business outcome (422), not an incident. If it is logged at ERROR and counted in the 5xx rate, on-call gets paged during every payday spike.- An error logged at every layer appears five times in Kibana/Loki with five different messages, making incident triage slower and multiplying PII exposure.
Core concepts
Errors are values
type error interface {
Error() string
}
Because errors are ordinary values, you can store them, compare them, wrap them, aggregate them and attach data. The explicit if err != nil is the price of seeing every failure path in code review.
Message conventions: lower-case, no trailing punctuation, describe the operation that failed, and let the chain read like a sentence:
create transfer tr_91: debit account acc_7: update balance: context deadline exceeded
Wrapping and inspecting
if err != nil {
return fmt.Errorf("debit account %s: %w", id, err) // %w keeps err in the chain
}
%wwraps (the result hasUnwrap() error).%vformats only — use it deliberately at a boundary when you don't want callers to depend on the cause.- Since Go 1.20,
fmt.Errorfaccepts multiple%wverbs, anderrors.Join(errs...)combines errors; both produceUnwrap() []error, andIs/Assearch the whole tree. errors.Is(err, target)reports whether any error in the chain equalstarget(or has anIs(error) boolmethod that says so).errors.As(err, &target)finds the first error in the chain assignable totarget's type and sets it.- Go 1.26 adds the generic
errors.AsType[E](err) (E, bool), which avoids declaring a target variable.
var insuf *payment.InsufficientFundsError
if errors.As(err, &insuf) {
fmt.Println(insuf.Available)
}
// Go 1.26+
if insuf, ok := errors.AsType[*payment.InsufficientFundsError](err); ok {
fmt.Println(insuf.Available)
}
Go errors carry no stack trace. Contextual wrapping ("debit account acc_7") usually locates the failure faster than a stack would; for the rest, use trace spans and log stack traces only for panics.
Sentinel, typed and opaque errors
| Style | Example | Caller checks with | Use when |
|---|---|---|---|
| Sentinel | var ErrNotFound = errors.New("not found") | errors.Is | Caller branches on the condition; no extra data needed |
| Typed | type InsufficientFundsError struct{ ... } | errors.As / errors.AsType | Caller needs fields (amounts, retry-after, field name) |
| Behavioural | interface{ Timeout() bool } | errors.As into the interface | Cross-package classification without importing the type (net.Error) |
| Opaque | fmt.Errorf("parse row %d: %w", n, err) | only err != nil | Caller can't do anything specific — most errors |
Sentinels and typed errors are part of your package's API. Exporting one is a commitment; don't export what callers shouldn't branch on.
A payment domain error vocabulary
package payment
import (
"errors"
"fmt"
)
var (
ErrNotFound = errors.New("payment: not found")
ErrInsufficientFunds = errors.New("payment: insufficient funds")
ErrDuplicateRequest = errors.New("payment: duplicate request")
ErrAccountFrozen = errors.New("payment: account frozen")
ErrUnknownOutcome = errors.New("payment: outcome unknown")
)
// InsufficientFundsError carries the numbers the API and the audit log need.
type InsufficientFundsError struct {
AccountID string
Available int64 // minor units
Requested int64
}
func (e *InsufficientFundsError) Error() string {
return fmt.Sprintf("account %s: insufficient funds: available %d, requested %d",
e.AccountID, e.Available, e.Requested)
}
// Unwrap ties the typed error to its sentinel, so both
// errors.Is(err, ErrInsufficientFunds) and errors.As work.
func (e *InsufficientFundsError) Unwrap() error { return ErrInsufficientFunds }
// DuplicateRequestError lets the API return the original resource.
type DuplicateRequestError struct {
IdempotencyKey string
ExistingID string
}
func (e *DuplicateRequestError) Error() string {
return fmt.Sprintf("idempotency key %q already used by %s", e.IdempotencyKey, e.ExistingID)
}
func (e *DuplicateRequestError) Unwrap() error { return ErrDuplicateRequest }
The Unwrap to a sentinel is a useful trick: generic code (metrics, HTTP mapping) checks the sentinel; specific code extracts details with As.
Classifying provider errors for retries is where the vocabulary pays off:
See Payments & Card Flows and Reconciliation & Settlement for what happens after ErrUnknownOutcome.
Translate at layer boundaries
Each layer wraps for context and translates errors that belong to a lower layer's vocabulary:
func (r *Repo) Insert(ctx context.Context, p payment.Payment) error {
_, err := r.pool.Exec(ctx,
`INSERT INTO payments (id, idempotency_key, amount_minor, currency)
VALUES ($1, $2, $3, $4)`,
p.ID, p.IdempotencyKey, p.Amount, p.Currency)
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" &&
pgErr.ConstraintName == "payments_idempotency_key_key" {
return &payment.DuplicateRequestError{IdempotencyKey: p.IdempotencyKey}
}
if err != nil {
return fmt.Errorf("insert payment %s: %w", p.ID, err)
}
return nil
}
Two judgement calls:
- Wrapping the raw driver error with
%wkeeps diagnostics but lets callerserrors.Asinto*pgconn.PgError— coupling your use case to PostgreSQL. Translate everything callers might branch on; wrapping the rest for logs is fine. - At public API boundaries (a library, an RPC response) use
%vor a fresh error for anything internal.
panic and recover
panic unwinds the goroutine, running deferred calls; recover() inside a deferred function in the same goroutine stops the unwinding and returns the panic value.
Use panic for:
- Programmer errors and violated invariants: impossible
switchdefault, nil dependency passed to a constructor at startup. Must-style helpers during initialisation:regexp.MustCompile,template.Must.
Never use it for: validation failures, not-found, declined payments, or as an exception-style control flow across packages.
Recover at goroutine boundaries:
func Recoverer(log *slog.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
v := recover()
if v == nil {
return
}
if v == http.ErrAbortHandler { // deliberate abort: let net/http handle it
panic(v)
}
log.ErrorContext(r.Context(), "panic in handler",
"panic", v, "stack", string(debug.Stack()))
http.Error(w, "internal error", http.StatusInternalServerError)
}()
next.ServeHTTP(w, r)
})
}
}
Facts interviewers probe:
net/httpalready recovers panics per request (logging them and closing the connection), but goroutines you start are not protected. A panic in a background goroutine crashes the whole service — every in-flight payment included. Wrap long-lived worker goroutines with a recover-and-report helper, and still treat every recovered panic as a bug.- A runtime
fatal error(concurrent map writes, out of memory, deadlock "all goroutines are asleep") is not a panic and cannot be recovered. - Since Go 1.21,
panic(nil)becomes a*runtime.PanicNilError, sorecover()returningnilreliably means "no panic". - After recovering mid-update, state may be half-modified. Recovering is safe for request-scoped state; it is dangerous for shared in-memory state (a cache, a balance map). Sometimes crashing and restarting is the correct choice.
Errors and defer
Errors from Close on a written file or a committed resource matter — that's when buffered data hits disk. Capture them with a named result:
func writeStatement(path string, lines []Line) (err error) {
f, err := os.Create(path)
if err != nil {
return fmt.Errorf("create %s: %w", path, err)
}
defer func() {
if cerr := f.Close(); cerr != nil {
err = errors.Join(err, fmt.Errorf("close %s: %w", path, cerr))
}
}()
w := bufio.NewWriter(f)
for _, l := range lines {
if _, err := fmt.Fprintf(w, "%s,%d,%s\n", l.Date, l.Amount, l.Ref); err != nil {
return fmt.Errorf("write line: %w", err)
}
}
return w.Flush()
}
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
Wrap with %w | Full chain, Is/As work | Exposes cause as API | Inside your service, between your own layers |
Format with %v | Hides implementation | Callers can't inspect cause | Library/API boundaries |
| Sentinel errors | Simple, cheap, comparable | No data; exported forever | Branchable conditions (not found, duplicate) |
| Typed errors | Carry structured data | More code; pointer vs value receiver must match As target | Callers need details (balances, field names) |
Error kinds (one type with a Kind field) | Uniform mapping to codes | Can become a god type | Larger codebases wanting one mapping table |
| Panic + recover | Unwinds deep stacks | Hides control flow, unsafe for shared state | Bugs, init-time Must, goroutine boundaries |
| Crash and restart | Clean state guaranteed | Drops in-flight work | Corrupted shared state; supervisors (Kubernetes) restart you |
In practice
Map domain errors at the HTTP edge
One function owns the mapping; handlers just call it. The response uses RFC 9457 problem details (application/problem+json).
type problem struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail,omitempty"`
}
func writeError(w http.ResponseWriter, r *http.Request, log *slog.Logger, err error) {
p := problem{Type: "about:blank", Title: "internal error", Status: http.StatusInternalServerError}
var insuf *payment.InsufficientFundsError
var dup *payment.DuplicateRequestError
switch {
case errors.As(err, &insuf):
p = problem{Type: "/errors/insufficient-funds", Title: "insufficient funds",
Status: http.StatusUnprocessableEntity,
Detail: fmt.Sprintf("available %d, requested %d", insuf.Available, insuf.Requested)}
case errors.As(err, &dup):
p = problem{Type: "/errors/duplicate-request", Title: "duplicate request",
Status: http.StatusConflict, Detail: "existing payment " + dup.ExistingID}
case errors.Is(err, payment.ErrNotFound):
p = problem{Type: "/errors/not-found", Title: "not found", Status: http.StatusNotFound}
case errors.Is(err, payment.ErrAccountFrozen):
p = problem{Type: "/errors/account-frozen", Title: "account frozen", Status: http.StatusForbidden}
case errors.Is(err, context.DeadlineExceeded):
p = problem{Type: "about:blank", Title: "timeout", Status: http.StatusGatewayTimeout}
case errors.Is(err, context.Canceled):
log.InfoContext(r.Context(), "client canceled request", "err", err)
return // client is gone; nothing useful to write
}
if p.Status >= 500 {
log.ErrorContext(r.Context(), "request failed", "err", err, "status", p.Status)
} else {
log.InfoContext(r.Context(), "request rejected", "err", err, "status", p.Status)
}
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(p.Status)
_ = json.NewEncoder(w).Encode(p)
}
For a genuinely idempotent replay many APIs return the original response (200/201) instead of 409 — decide per endpoint and document it.
Same table for gRPC
| Domain error | HTTP | gRPC code |
|---|---|---|
| validation failure | 400 | InvalidArgument |
ErrNotFound | 404 | NotFound |
ErrDuplicateRequest | 409 (or replay original) | AlreadyExists |
ErrInsufficientFunds | 422 | FailedPrecondition |
ErrAccountFrozen | 403 | PermissionDenied or FailedPrecondition |
| optimistic-lock conflict | 409 | Aborted (client may retry the whole transaction) |
| rate limited | 429 | ResourceExhausted |
context.DeadlineExceeded | 504 | DeadlineExceeded |
ErrUnknownOutcome | 502/504 with a status-check link | Unknown or DeadlineExceeded + documented follow-up |
| anything else | 500, generic body | Internal, generic message |
func toStatus(err error) error {
switch {
case errors.Is(err, payment.ErrNotFound):
return status.Error(codes.NotFound, "payment not found")
case errors.Is(err, payment.ErrDuplicateRequest):
return status.Error(codes.AlreadyExists, "duplicate request")
case errors.Is(err, payment.ErrInsufficientFunds):
return status.Error(codes.FailedPrecondition, "insufficient funds")
case errors.Is(err, context.DeadlineExceeded):
return status.Error(codes.DeadlineExceeded, "deadline exceeded")
default:
return status.Error(codes.Internal, "internal error")
}
}
// Unary interceptor applying the mapping for every RPC.
func ErrorInterceptor(ctx context.Context, req any, _ *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (any, error) {
resp, err := handler(ctx, req)
if err != nil {
return nil, toStatus(err)
}
return resp, nil
}
The code choice matters to clients: many retry policies retry Unavailable automatically but not FailedPrecondition. Mapping insufficient funds to Unavailable would cause retry storms. See RPC & gRPC.
Log once, at the edge
Rule: either handle the error (log it, convert it, recover from it) or return it — not both. Lower layers add context by wrapping; the edge (HTTP handler, gRPC interceptor, queue consumer) logs once with request ID, trace ID, operation and the full chain.
- Log level follows your responsibility: 4xx outcomes at INFO/WARN, 5xx at ERROR.
- Never put PANs, CVVs, passwords or full account numbers in error strings — they end up in logs, traces and support tickets (see Compliance: PCI DSS, KYC/AML, Data Protection).
- Count errors by class (sentinel), not by message, in metrics:
payment_errors_total{kind="insufficient_funds"}.
Common pitfalls
- Comparing with
==after wrapping —err == ErrNotFoundis false once anyone adds%wcontext. Useerrors.Is. - Typed nil returned as
error— function returns*MyErr(nil); caller sees a non-nil error (see Interfaces & Composition). errors.Aswith the wrong target type — methods on*Tbut target isT(or vice versa);Assilently never matches.go vetcatches passing a non-pointer target.- Log and return — the same failure logged at repo, use case and handler; alert noise and duplicated PII.
- Swallowing errors —
_ = tx.Rollback()is fine after a failure;_ = tx.Commit()is a data-loss bug. - Retrying non-idempotent operations on timeout — double charges. Classify unknown outcomes separately.
- Leaking internals — SQL text or driver messages in API responses help attackers and break clients when you change databases.
- Recovering in the wrong goroutine — a
recoverinmaindoesn't catch a panic inside a goroutine started by a handler. - Ignoring
Closeerrors on writers — truncated settlement files that "succeeded". - Error strings as control flow —
strings.Contains(err.Error(), "duplicate key")breaks on driver upgrades and locales. Use codes (pgErr.Code == "23505").
Interview angle
Common prompts: "How do you handle errors in Go compared to exceptions?", "errors.Is vs errors.As?", "When would you panic?", "How do you map errors to HTTP status codes in a payment API?", "A PSP call timed out — what do you do?"
A strong answer: errors are values, wrapped with context, inspected with Is/As; sentinels and typed errors form a deliberate API; translation happens at layer boundaries; one mapping table at the edge; log once; panics only for bugs, recovered at goroutine boundaries. For the timeout question, the architect-level answer is unknown outcome: keep the idempotency key, query status, mark the payment pending, and reconcile from settlement files — never "just retry" and never "just fail".
Follow-ups: "How do you add stack traces?" (you mostly don't; context + tracing; stack on panic), "What's errors.Join for?" (cleanup paths, validating many fields), "How do you avoid leaking database errors?" (translate in the repository).
Red flags: panic for validation, string matching on error messages, logging at every level, mapping every error to 500.
Self-check
1. What is the difference between errors.Is and errors.As, and why can't you use == or a type assertion instead?
Is checks whether any error in the chain equals a target value (sentinels); As finds the first error of a given type and assigns it. Both unwrap through %w, errors.Join and custom Unwrap/Is methods. == and type assertions only look at the outermost error, so they break as soon as someone adds context.
2. Why does InsufficientFundsError implement Unwrap() error returning ErrInsufficientFunds?
So code that only cares about the class (HTTP mapping, metrics, retry policy) can use errors.Is(err, ErrInsufficientFunds) while code that needs the numbers uses errors.As. One error value serves both styles without duplication.
3. Where should a PostgreSQL unique-violation error be translated into ErrDuplicateRequest, and why there?
In the repository adapter, which is the only layer that knows it's talking to PostgreSQL (error code 23505 and the constraint name). If the driver error leaks upward, use cases and handlers become coupled to the database, and swapping or mocking storage changes behaviour.
4. A background goroutine that publishes outbox events panics on a malformed row. What happens, and how should the service be structured?
The whole process crashes — net/http's per-request recovery doesn't cover goroutines you start. Wrap the worker loop iteration in a recover that logs with the row ID, marks the row as poisoned/dead-lettered, increments a metric, and continues. Still fix the bug: recovered panics are incidents.
5. Scenario: POST /payments to the card processor times out after 30 s. List the steps your service takes.
Return/record ErrUnknownOutcome, not "failed". Keep the payment in a pending state with the idempotency key, run a status inquiry (or retry with the same idempotency key if the provider guarantees dedup), and fall back to settlement-file reconciliation. Tell the client the outcome is pending with a status URL; do not create a second payment.
6. Why is "log and return" harmful, and what's the rule instead?
The same failure appears many times with different messages, inflating alert counts, confusing triage and multiplying sensitive data in logs. Rule: lower layers wrap with context and return; the edge logs once with request/trace IDs and maps to a response.
7. When is recovering from a panic and continuing unsafe?
When the panic interrupted a mutation of shared state — e.g. half-updated in-memory balances or a cache under a lock that was never released. The process may now violate invariants. For request-scoped state, recover-and-500 is fine; for shared state, crash and let the orchestrator restart you.
Exercise
Implement the error layer of a transfer service:
- Package
transferwith sentinels (ErrNotFound,ErrInsufficientFunds,ErrDuplicateRequest,ErrUnknownOutcome) and typed errors thatUnwrapto them. - A repository (in-memory is fine) that simulates a unique violation and translates it.
- An HTTP handler for
POST /transfersusing a singlewriteErrormapping function with problem-details responses; a gRPC-styletoStatuswith the same table. - A recover middleware and a
safeGo(fn)helper for background workers. - Tests: table-driven test of the mapping (error in, status out), a test that a wrapped error (three levels of
%w) still maps correctly, and a test that the handler logs exactly once per failed request (use asloghandler that counts records).
Done when: no handler inspects error strings, every exported error is reachable through errors.Is, and the logging test passes.
Further reading
- Go blog: "Error handling and Go" (Andrew Gerrand) and "Working with Errors in Go 1.13" (Damien Neil, Jonathan Amsterdam).
- Go blog: "Errors are values" (Rob Pike).
- Go blog: "Defer, Panic, and Recover" (Andrew Gerrand).
errorspackage documentation —Is,As,Join,AsType.- Dave Cheney, "Don't just check errors, handle them gracefully" (GopherCon talk / blog).
- Teiva Harsanyi, 100 Go Mistakes and How to Avoid Them — error management chapter.
- RFC 9457, "Problem Details for HTTP APIs".
- gRPC documentation: status codes and their retry semantics.
Related
- Idempotency & Exactly-Once — what
ErrDuplicateRequestprotects. - Resilience Patterns — which errors to retry, circuit-break or fail fast.
- Building Production Services — where the edge mapping and logging live.
- API Design (REST, gRPC, GraphQL) — error contracts for clients.
- Payments & Card Flows — authorization, capture and the unknown-outcome problem.
- Common Pitfalls — more error-handling traps.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).