Skip to content

Errors, Wrapping, Panic, Recover & Defer ​

"Values can be programmed, and since errors are values, errors can be programmed." — Rob Pike, Errors are values, The Go Blog, 12 January 2015

Summary: In Go a failure is an ordinary value of the error interface that you return, wrap with context and inspect with errors.Is/errors.As; panic is for bugs and impossible states, recover turns a panic back into a value at a boundary, and defer is the cleanup mechanism both paths share. Focus: The error interface, errors.New, fmt.Errorf with %w (one or many), errors.Is/As/Unwrap/Join/AsType, sentinel vs error type vs opaque error, custom error types, handle once instead of log and return, io.EOF and context errors as signals, defer order and argument evaluation, panic/recover/re-panic, goroutine and net/http boundaries, os.Exit and log.Fatal, exit codes, stack traces, gRPC status and Problem Details, and the linters (errcheck, errorlint, wrapcheck). Learning goal: Design the errors of a package as part of its API, add context exactly once per layer, decide in one place what an error means for the caller, and know precisely which code runs (and which does not) when something panics or exits.

This page is the complete reference for failure handling inside a Go program: the values, the wrapping tree, the panic machinery and the cleanup rules. It does not re-teach its neighbours. Function syntax and closures are in Functions; why a nil pointer inside an interface is not a nil interface is in Interfaces, Type Assertions, Type Switches & any (we show the error-specific trap only); how a context.Context is cancelled and propagated is in context; collecting errors from many goroutines with errgroup is in Worker Pools, Pipelines; a full middleware chain (logging, CORS, rate limiting) is in Middlewares; signal handling and graceful shutdown are in OS Processes, Signals & Graceful Shutdown; golangci-lint configuration is in Project Layout, golangci-lint. Language-neutral fault tolerance (retries, bulkheads, error taxonomies across a system) lives in Error & Exception Handling and Fault Tolerance in Design and Timeouts, Retries & Jitter.

Page map ​

If you are looking forGo to
Tables you can memorise in one minuteEverything in one minute
Why Go has no exceptionsWhy it exists
Go 1.0 to 1.27: what changed and whenWhere it comes from
type error interface, errors.New, message styleThe error interface
fmt.Errorf("...: %w", err), %w vs %vWrapping
errors.Is, errors.As, errors.Unwrap, errors.AsTypeInspecting the chain
errors.Join, several %w in one callMultiple errors
Sentinel vs error type vs opaque error (Cheney)Three styles
Custom error types with fields, custom Is, typed nilCustom error types
Handle once, don't log and return, wrap without leakingHandle once
io.EOF, context.Canceled, context.DeadlineExceeded, errors.ErrUnsupportedSignals that are not failures
defer: LIFO, argument evaluation, loops, costdefer
panic, runtime.Error, panic(nil)panic
recover, re-panicrecover and re-panic
Goroutines and net/http as panic boundariesBoundaries
os.Exit, log.Fatal, exit codesExiting
debug.Stack, pkg/errorsStack traces
errcheck, errorlint, wrapcheck, go vetLinters
Bad code and the fix, side by sideGo
Exact runtime and vet messagesMechanics
Tested solutions to each classic problemSolving the classic problems
Which mechanism for which situationChoosing
Exceptions, Throwable, finally vs GoFor PHP/Laravel developers
Errors across processes, RPC and servicesIn architecture
Run every message yourselfLab
Wrong beliefs, cheat sheet, self-check, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The toolbox. Every row is unpacked in the concept catalogue.

ToolIn plain wordsTiny exampleSince
errorAny value with an Error() string method; nil means successfunc Open(name string) (*File, error)Go 1.0
errors.NewA new, unique error value with a fixed textvar ErrNotFound = errors.New("order not found")Go 1.0
fmt.Errorf + %wAdd context and keep the cause inspectablefmt.Errorf("load order %s: %w", id, err)Go 1.13
fmt.Errorf + %vAdd context, hide the cause (text only)fmt.Errorf("query: %v", err)Go 1.0
errors.Is"Is this error, or anything it wraps, that value?"errors.Is(err, fs.ErrNotExist)Go 1.13
errors.As"Find the first error of this type and give it to me"var pe *fs.PathError; errors.As(err, &pe)Go 1.13
errors.AsTypeGeneric As, returns the value and a boolpe, ok := errors.AsType[*fs.PathError](err)Go 1.26
errors.UnwrapOne step down a single-cause chainerrors.Unwrap(err)Go 1.13
errors.Join / many %wOne error wrapping severalerrors.Join(errA, errB)Go 1.20
errors.ErrUnsupportedStandard "this operation is not supported"errors.Is(err, errors.ErrUnsupported)Go 1.21
deferRun this call when the function returns, whatever pathdefer f.Close()Go 1.0
panicStop this goroutine's normal flow and unwindpanic("unreachable")Go 1.0
recoverInside a deferred call: stop the unwinding, get the valueif v := recover(); v != nil { ... }Go 1.0

Error, panic or exit.

MechanismWho sees itDo defers run?Exit status if unhandledUse it for
return errThe direct callerYes, normally— (the caller decides)Every expected failure: input, I/O, network, missing rows
panic(v)Deferred calls up the same goroutineYes, while unwinding2, with panic: ... and stacksBugs, broken invariants, Must* helpers, failed init
runtime panicSame as panic, value is a runtime.ErrorYes2Index out of range, nil map write, nil dereference, failed type assertion
os.Exit(code)The parent processNocodeOnly in main, after run() has returned
log.Fatal(...)The parent processNo1Small tools; never in libraries or after resources are open
fatal error: (runtime)Nobody can recover itNo2Deadlock, concurrent map writes, out of memory

The five defer rules.

RuleExampleResult
Deferred calls run in LIFO orderfor i := 0; i < 3; i++ { defer fmt.Print(i) }prints 210
Arguments are evaluated at the defer statementx := 1; defer fmt.Println(x); x = 2prints 1
A closure reads variables when it runsdefer func() { fmt.Println(x) }(); x = 2prints 2
Deferred closures can change named resultsfunc f() (n int) { defer func() { n *= 7 }(); return 6 }returns 42
Defers belong to the function, not the blockfor ... { f, _ := os.Open(p); defer f.Close() }every file stays open until the function returns

Why it exists ​

Every program meets failures that are not bugs: a file is missing, a peer resets the connection, a row is not there, the user typed letters into a number field. Languages with exceptions send these through a second, invisible control path; any call might jump out of the function. Go's designers chose to keep the normal path and the failure path in the same place: a function that can fail says so in its signature, and the caller writes what happens next right after the call. The FAQ states the reasoning: coupling exceptions to a control structure "results in convoluted code" and "tends to encourage programmers to label too many ordinary errors, such as failing to open a file, as exceptional."

That choice has a price — if err != nil everywhere — and three consequences this page is about. First, errors are values, so you can design them: give them identity (sentinels), structure (types with fields) or keep them opaque. Second, because each layer returns the error by hand, each layer can add context, and the standard library since Go 1.13 lets it do so without destroying the original (%w). Third, there is still a crash path for genuine bugs (panic), with a narrow escape hatch (recover) and a cleanup mechanism (defer) that runs on both paths.

Exceptions (PHP, Java, Python)Go errors
Failure travels on a hidden path; any call may throwFailure is in the signature: (T, error)
Handling is optional; uncaught means crashHandling is required by convention and by linters (errcheck)
Stack trace attached automaticallyNo stack trace; context is added by wrapping with messages
try/catch by class hierarchyerrors.Is by identity, errors.As by type, behaviour by interface
finally for cleanupdefer for cleanup, on every path including panics
Throwing is cheap to write, expensive to reason aboutReturning is verbose to write, cheap to reason about
One mechanism for bugs and for expected failureserror for expected failures, panic for bugs

The analogy we reuse on this page: a parcel and its shipping labels. A failure is a parcel sent back up the chain of people who handed you the job. Each person may stick a label on it saying what they were doing ("load order o-9", "checkout"): that is wrapping with %w, and the original parcel is still inside. A person may also repack it in a plain box with only a note ("internal error"): that is %v or translation, and nobody upstream can open it. Only the person at the front desk (the boundary) opens it, decides what to tell the customer, and writes one entry in the log book. If someone in the warehouse finds the building on fire, they do not send a parcel; they pull the alarm (panic). On the way out every person runs their own clean-up checklist in reverse order of when they started tasks (defer, LIFO). The front desk may have a fire marshal who stops the evacuation for one room (recover). Pulling the main power switch (os.Exit) skips every checklist.

Three common misunderstandings, up front ​

  1. "panic/recover is Go's try/catch." It is not a control-flow tool. A panic crosses package boundaries only by accident; the Go team's rule (Effective Go) is that a package converts its internal panics into error values and "does not expose panics to its client." Use error for everything a caller might reasonably handle.
  2. "Wrapping with %w is always better than %v." Wrapping makes the cause part of your API. The Go 1.13 blog: "Wrap an error to expose it to callers. Do not wrap an error when doing so would expose implementation details." Wrapping sql.ErrNoRows from a repository promises callers that you will keep returning it.
  3. "A recover in main protects my whole program." recover works only for the goroutine it runs in and only when called directly by a deferred function. A panic in any goroutine you started without its own recover kills the process, main's recover notwithstanding. Proven in the lab.

Where it comes from ​

Go 1.0 (2012) shipped the predeclared error interface, errors.New, fmt.Errorf, and the three builtins defer, panic, recover, all of which had been described in Andrew Gerrand's blog post Defer, Panic, and Recover (4 August 2010), which lists "three simple rules" for defer. Error handling and Go (12 July 2011) set the conventions: compare against sentinel values, use types such as *os.PathError when callers need details. Rob Pike's Errors are values (12 January 2015) argued that repetitive if err != nil is a design smell you can program away (the bufio.Scanner-style "sticky error").

The community years. Dave Cheney's talk and post Don't just check errors, handle them gracefully (27 April 2016) named three strategies — sentinel errors, error types and opaque errors — recommended "assert errors for behaviour, not type", and said "you should only handle errors once." His package github.com/pkg/errors added errors.Wrap, errors.Cause and stack traces captured at the point of creation; it is now in maintenance mode ("With the upcoming Go2 error proposals this package is moving into maintenance mode").

Go 1.13 (2019) brought wrapping into the standard library: an error may have an Unwrap() error method, fmt.Errorf gained %w, and errors.Is, errors.As, errors.Unwrap walk the chain (Working with Errors in Go 1.13, Damien Neil and Jonathan Amsterdam, 17 October 2019). Go 1.14 made most defers "almost zero overhead" with open-coded defers. Go 1.20 allowed an error to wrap several errors (Unwrap() []error), several %w in one fmt.Errorf, and added errors.Join. Go 1.21 made panic(nil) a run-time panic of type *runtime.PanicNilError (so recover never returns nil during a panic) and added errors.ErrUnsupported. Go 1.22's vet started reporting defer log.Println(time.Since(t)). Go 1.23 made net.DNSError wrap timeouts and cancellations so errors.Is(err, context.DeadlineExceeded) works on them. Go 1.25 changed the crash output of a recovered and re-panicked value to panic: PANIC [recovered, repanicked], and fixed a compiler bug (introduced in 1.21) that delayed nil checks so code using f.Name() before checking err from os.Open ran "successfully"; it now panics as the spec requires. Go 1.26 added the generic errors.AsType. Go 1.27's vet reports fmt.Errorf("...: %w", p) when p is a *E and E itself implements error.

This page was checked against the Go specification as published on go.dev (language version go1.27), Effective Go, the Go FAQ, the release notes 1.13–1.27, and the standard library source on go.dev/src. The snippets declare go 1.24 and were compiled, vetted and tested with Go 1.27.4; features newer than 1.24 (errors.AsType, the 1.25 crash text) are labelled where they appear.

The concept catalogue ​

Each block: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, behaviour per situation, and the fix. Full, tested code is in Solving the classic problems.

The error interface and errors.New Must-know ​

In plain words: an error is any value that can describe itself as a string. A function that can fail returns it as its last result; nil means "it worked".

Common misunderstanding: "An error is a string." The text is for humans; programs must never branch on it. Two calls of errors.New("x") produce two different errors that are not equal, because identity, not text, is what == and errors.Is compare. A second one: "if err != nil, the other results are garbage, so I can still use them a little." Go 1.25 fixed a compiler bug precisely because programs did that: f, err := os.Open(p); name := f.Name() before the check must panic when f is nil.

Definition: the spec: type error interface { Error() string } — "the conventional interface for representing an error condition, with the nil value representing no error." errors.New(text) returns a pointer to an unexported struct, so each call is a distinct value. The Code Review Comments wiki: "Error strings should not be capitalized (unless beginning with proper nouns or acronyms) or end with punctuation, since they are usually printed following other context."

text
1  caller:  n, err := r.Read(buf)
2  callee:  returns (0, io.EOF)            -> results + error, error last
3  caller:  if err != nil { ... }          -> check immediately, before using n? (Read: use n first, see io.EOF)
4  caller:  return fmt.Errorf("read header: %w", err)
5  printed: "parse config: read header: EOF"   -> lowercase, colon-separated, no final period

Real scenario: a payment client returns errors.New("Card declined."); the boundary prints charge order o-9: Card declined.: retry later — capitals and punctuation in the middle. A billing job compares err.Error() == "timeout" and silently stops retrying when the library changes the text to "i/o timeout". A handler uses resp after client.Do returned an error and crashes on a nil body.

SituationReturnWhy
Success(value, nil)nil error means success; never a non-nil "OK" error
Expected failure(zero value, err)Callers must not rely on other results unless documented (io.Reader is the documented exception)
Partial successDocument it: (n, err) like Read/WriteCallers then use n before checking err
"Not found" in a lookupA sentinel or (T, bool)The wiki's In-Band Errors section: do not return "" or -1

Fix / how to use it: return error (the interface type, never a concrete *MyErr) as the last result; check it on the next line; write messages lowercase, without trailing punctuation, naming the operation and the key identifier. Define reusable errors once at package level with errors.New.

Wrapping with fmt.Errorf and %w Must-know ​

In plain words: wrapping adds "what I was doing" to an error while keeping the original inside, so a caller can still ask "was it a not-found?".

Common misunderstanding: "%w and %v print the same, so they are the same." They print the same text; only %w creates an Unwrap method. The reverse mistake is to wrap everything: wrapping a driver's error makes that driver part of your public contract.

Definition: fmt.Errorf with one %w returns an error whose Unwrap() error returns the operand; "If there is more than one %w verb, the returned error will implement an Unwrap method returning a []error containing all the %w operands in the order they appear in the arguments." The operand must implement error; otherwise vet reports fmt.Errorf format %w has arg "not an error" of wrong type string and at run time you get %!w(string=...). A nil operand prints %!w(<nil>). The Go 1.13 blog's rule: "wrapping an error makes that error part of your API. If you don't want to commit to supporting that error as part of your API in the future, you shouldn't wrap the error."

text
1  repo.Get("o-9")           -> ErrNotFound
2  service.Load               -> fmt.Errorf("load order %s: %w", id, err)   // wraps
3  handler                    -> errors.Is(err, ErrNotFound) == true -> 404
4  ---- same with %v ----
5  service.Load               -> fmt.Errorf("load order %s: %v", id, err)   // flattens
6  handler                    -> errors.Is(err, ErrNotFound) == false -> 500 (wrong)

Real scenario: an order API that returned 500 for every missing order after a refactor replaced %w with %v; a file-import job that cannot tell "permission denied" from "not found" because the cause was flattened; a library upgrade that broke a caller's errors.Is(err, sql.ErrNoRows) because the library stopped wrapping a detail it never meant to expose.

You wantVerbEffect
Caller may inspect the cause (it is part of your contract)%werrors.Is/As see through
Caller sees the text only (cause is an implementation detail)%vOpaque: logs keep the words, API keeps its freedom
Several causes inspectable%w ... %w (Go 1.20)Unwrap() []error
Your own meaning, original hiddenReturn your sentinel, or fmt.Errorf("...: %w", ErrMine)Translation at the boundary

Fix / how to use it: wrap with %w when the cause came from something the caller gave you or is a documented contract (io.Reader errors, context errors, your own sentinels); translate or use %v for storage and transport details. The opaque boundary snippet tests both sides.

errors.Is, errors.As, errors.Unwrap and errors.AsType Must-know ​

In plain words: Is asks "is that specific error anywhere inside?"; As asks "is there an error of this type inside? give it to me"; Unwrap peels one layer.

Common misunderstanding: "errors.Unwrap walks the whole tree." It only calls Unwrap() error; for an error with Unwrap() []error (from errors.Join or multiple %w) it returns nil. Use Is/As, which walk everything. Another: passing a value instead of a pointer to As — vet stops it with second argument to errors.As must be a non-nil pointer to either a type that implements error, or to any interface type.

Definition: the errors package doc: "Successive unwrapping of an error creates a tree. The Is and As functions inspect an error's tree by examining first the error itself followed by the tree of each of its children in turn (pre-order, depth-first traversal)." Is matches by == or by an Is(error) bool method on a node; As matches by assignability or an As(any) bool method, and sets the target. errors.AsType[E](err) (E, bool) (Go 1.26) is "a generic version of As. It is type-safe, faster, and, in most cases, easier to use."

The error tree and the order errors.Is / errors.As visit it1 fmt.Errorf("checkout: %w; %w", a, b)Unwrap() []error2 a = fmt.Errorf("reserve: %w", err)Unwrap() error4 b = errors.Join(e1, e2)Unwrap() []error, text joined by "\n"3 ErrOutOfStock (sentinel)leaf: no Unwrap5 *PaymentErrorCode: "card_declined"6 context.DeadlineExceedederrors.Is(err, ErrOutOfStock) stops at 3. errors.As(err, &pe) for *PaymentError stops at 5.errors.Is(err, context.DeadlineExceeded) reaches 6. errors.Unwrap(err) on node 1 returns nil:it only follows Unwrap() error, never Unwrap() []error. Each node may also define Is(error) bool or As(any) bool.
text
1  err := fmt.Errorf("checkout: %w; %w", a, b)       // node 1, two children
2  errors.Is(err, ErrOutOfStock)                       // visits 1, 2, 3 -> true at 3
3  errors.As(err, &pe)        (pe *PaymentError)       // visits 1, 2, 3, 4, 5 -> true at 5
4  errors.Is(err, context.DeadlineExceeded)            // visits ... 6 -> true
5  errors.Unwrap(err)                                  // nil: node 1 has Unwrap() []error

Real scenario: a retry loop that checks err == context.DeadlineExceeded and never matches because the driver wrapped it (errorlint catches this); a file sync that needs the path from *fs.PathError to report which file failed; a validator returning errors.Join of five field errors where the handler wants the first *FieldError.

QuestionBefore 1.13Since 1.13Since 1.26
Is it io.ErrUnexpectedEOF?err == io.ErrUnexpectedEOFerrors.Is(err, io.ErrUnexpectedEOF)same
Give me the *fs.PathErrorpe, ok := err.(*fs.PathError)var pe *fs.PathError; errors.As(err, &pe)pe, ok := errors.AsType[*fs.PathError](err)
Does anything say "timeout"?ne, ok := err.(net.Error)var ne net.Error; errors.As(err, &ne) && ne.Timeout()errors.AsType[net.Error](err)
One level downpkgerrors.Cause(err)errors.Unwrap(err) (single-cause only)same

Fix / how to use it: never compare with == or type-assert an error you did not create on that line (exception: io.EOF from Read, see signals); use Is for values, As for types and behaviour interfaces. Our module declares go 1.24, so the snippets use errors.As; on 1.26+ AsType is the nicer spelling.

errors.Join and multiple %w Important ​

In plain words: sometimes several things fail at once — three invalid form fields, two files that failed to close. errors.Join bundles them into one error that still answers Is/As for each member.

Common misunderstanding: "errors.Join(nil, nil) returns an empty, non-nil error." It returns nil: "Any nil error values are discarded. Join returns nil if every value in errs is nil." Another: assuming a particular order in Is/As results beyond "first match in pre-order".

Definition: errors.Join(errs ...error) error; the result's text is the members' texts "with a newline between each string" and it implements Unwrap() []error. fmt.Errorf("op: %w; %w", a, b) does the same with your own formatting. You can implement Unwrap() []error yourself (the ValidationErrors type in the wrapping snippet). The package doc adds: "It is invalid for an Unwrap method to return an []error containing a nil error value."

text
1  closeA() -> nil
2  closeB() -> "disk full on flush"
3  closeC() -> "broken pipe"
4  errors.Join(nil, errB, errC).Error() == "disk full on flush\nbroken pipe"
5  errors.Is(joined, errC) == true;  errors.Join(nil, nil) == nil

Real scenario: a form with three invalid fields returns all three, not the first; shutting down a service closes the HTTP server, the DB pool and the Kafka producer and reports every failure; a batch import collects per-row errors up to a limit.

NeedUseNote
Many independent failures, default texterrors.JoinNewline-separated; good for logs, not for one-line messages
Two causes with your own sentencefmt.Errorf("x: %w; %w", a, b)Go 1.20+
Domain type with fields per itemYour type with Unwrap() []errorKeeps structure for the response body
First error from N goroutines, cancel the resterrgroup.GroupSee Worker Pools, Pipelines

Fix / how to use it: use errors.Join in cleanup paths (defer with a named result, shown in defer) and for validation; keep one-line messages for the primary error.

Sentinel errors, error types and opaque errors Must-know ​

In plain words: you can give callers three kinds of failure information: which error (a sentinel value), what details (a type with fields), or only that it failed (opaque). Each is a promise you have to keep.

Common misunderstanding: "Sentinels are bad, Cheney said so." Cheney's 2016 advice ("avoid sentinel errors") predates %w; his main objection was that wrapping breaks ==. With errors.Is a wrapped sentinel still matches. What remains true: every exported sentinel or type is API you cannot remove, and it creates an import dependency ("to check if an error is equal to io.EOF, your code must import the io package").

Definition: a sentinel error is an exported package-level value (io.EOF, sql.ErrNoRows, fs.ErrNotExist, http.ErrServerClosed) matched with errors.Is. An error type is an exported type implementing error that carries data (*fs.PathError{Op, Path, Err}, *strconv.NumError, *net.OpError), matched with errors.As. An opaque error promises nothing beyond non-nil; callers may only test for behaviour through small interfaces (interface{ Timeout() bool }). Cheney: "assert errors for behaviour, not type."

text
1  caller needs nothing but success/failure      -> opaque: return fmt.Errorf("sync: %v", err)
2  caller needs to branch on one condition       -> sentinel: var ErrNotFound = errors.New(...)
3  caller needs data (field, path, code)         -> type: type ValidationError struct{ Field, Reason string }
4  caller needs a property (retry? timeout?)     -> behaviour: interface{ Temporary() bool }

Real scenario: an HTTP handler needs 404 vs 500 (sentinel); a form needs the field name (type); a retry middleware only needs "may succeed later" across ten different drivers (behaviour); an analytics exporter's caller only logs the failure (opaque).

StyleStdlib exampleMatch withCaller couplingCarries data
Sentinel errorio.EOF, sql.ErrNoRows, fs.ErrNotExist, context.Cancelederrors.IsImports your package; value is APINo (text only)
Error type*fs.PathError, *strconv.NumError, *net.OpError, *json.SyntaxErrorerrors.AsImports your package; fields are APIYes
Behaviour interfacenet.Error (Timeout())errors.As into an interfaceOnly the method setThe answer to one question
Opaque errormost fmt.Errorf("...: %v")nothingNoneText for logs

Fix / how to use it: default to opaque; export a sentinel only for conditions callers must branch on (not found, conflict, closed); export a type when they need fields; expose behaviour through tiny interfaces. Translate the errors of your dependencies at your package boundary.

Custom error types with fields Important ​

In plain words: a custom error is your own struct with an Error() method, so it can carry the order ID, the field name or the upstream status code to whoever handles it.

Common misunderstanding: "Return *MyError from my function for type safety." A function declared to return *MyError that returns a nil *MyError through an error interface gives the caller a non-nil error: the interface holds a type and a nil pointer. The FAQ entry Why is my nil error value not equal to nil? is exactly this; the full interface mechanics are in Interfaces. Always return the error interface and a literal nil.

Definition: a type with method Error() string, usually with a pointer receiver; optionally Unwrap() error (it wraps a cause), Unwrap() []error (several), Is(target error) bool (custom equality, e.g. "any 5xx"), As(target any) bool (custom conversion). Go 1.27 vet: wrapping a pointer to a pointer-implemented error (%w with &e where e is *MyErr) is "usually a latent bug".

text
1  func Validate(...) error { var errs *ValidationErrors; ...; return errs }
2  errs == nil inside Validate                       -> true
3  caller: err := Validate(...)                       -> interface{type: *ValidationErrors, value: nil}
4  caller: err != nil                                 -> true  (the typed-nil trap)
5  fix:    if len(errs) == 0 { return nil }           -> literal nil interface

Real scenario: a REST API that returns 422 with {"field": "qty"} needs the field from a *ValidationError; a payment client exposes *DeclineError{Code: "insufficient_funds"}; an HTTP client wraps upstream responses in *HTTPStatusError{Code} with an Is method so errors.Is(err, &HTTPStatusError{Code: 500}) means "any 5xx".

MethodPurposeExample in this page's snippets
Error() stringHuman textorder o-2: invalid amount: must not be negative
Unwrap() errorExpose one cause*PanicError exposes a runtime.Error value
Unwrap() []errorExpose severalValidationErrors
Is(error) boolCustom equality*HTTPStatusError matches the status class
As(any) boolCustom conversionRare; prefer plain types
Temporary() bool / Timeout() boolBehaviour for callersretryable, net.Error

Fix / how to use it: pointer receivers, exported fields only for data callers need, no secrets in fields that end up in logs, and return nil (untyped) on success.

Handle once: add context, don't log and return Must-know ​

In plain words: at every step up the call stack, either deal with the error (and stop it there) or pass it up with a little more context. Never both.

Common misunderstanding: "Logging in every layer helps debugging." It produces three log lines for one failure, none of which has the full picture, and the boundary logs it a fourth time. Cheney: "Handling an error means inspecting the error value, and making a decision" — logging is a decision; returning it is another; "making more than one decision in response to a single error is also problematic."

Definition: handle once = exactly one place inspects the error and acts (retry, fallback, translate to a status code, print and exit). All others wrap and return. The Code Review Comments wiki: "Do not discard errors using _ variables. If a function returns an error, check it to make sure the function succeeded. Handle the error, return it, or, in truly exceptional situations, panic."

text
     log and return (before)                         handle once (after)
1    repo:    log "no rows"; return err              repo:    return ErrNotFound
2    service: log "load failed: no rows"; return     service: return fmt.Errorf("load order o-9: %w", err)
3    handler: log "request failed"; write 500        handler: errors.Is -> 404; log once with request id
4    => 3 lines, wrong status                        => 1 line: "load order o-9: order not found"

Real scenario: an on-call engineer who sees "no rows in result set" logged 40 000 times per minute from a repository that also returned it; a queue consumer that logs "failed" and then also returns the error so the framework logs and retries it; a CLI that prints the error in a helper and again in main.

LayerDoesDoes not
Leaf (driver, repository)Translate foreign errors into your package's meaningLog, choose HTTP codes
Middle (service, use case)Wrap with the operation and key IDsLog, retry blindly, repeat information the callee already wrote
Boundary (handler, consumer, main)Inspect once, decide, log once with request context, respondRe-wrap, swallow silently

Fix / how to use it: each wrap adds only what the callee could not know (fmt.Errorf("load order %s: %w", id, err), not "error: failed to: %w"); the boundary adapter is the one place with slog calls. See the HTTP boundary snippet.

Signals that are not failures: io.EOF, context errors, errors.ErrUnsupported Important ​

In plain words: some "errors" are messages: "the input ended normally", "the caller gave up", "this feature is not available here". Treat them as signals, not incidents.

Common misunderstanding: "io.EOF is a failure, so wrap it like any other." The io package documents the opposite: "Read must return EOF itself, not an error wrapping EOF, because callers will test for EOF using ==." "Functions should return EOF only to signal a graceful end of input. If the EOF occurs unexpectedly in a structured data stream, the appropriate error is either ErrUnexpectedEOF or some other error giving more details." A second one: logging context canceled at error level — it means the client left, not that you broke.

Definition: io.EOF (end of input), io.ErrUnexpectedEOF (input ended mid-record: a real error), context.Canceled ("returned by Context.Err when the context is canceled for some reason other than its deadline passing", text context canceled), context.DeadlineExceeded (text context deadline exceeded; also satisfies net.Error with Timeout() == true), errors.ErrUnsupported ("a standardized way to indicate that a requested operation may not be performed because it is unsupported", Go 1.21; errors.Is(http.ErrNotSupported, errors.ErrUnsupported) is true).

text
1  for { n, err := r.Read(buf); process(buf[:n]); if err == io.EOF { break }; if err != nil { return err } }
2  ReadFull 3 bytes from "ab"           -> io.ErrUnexpectedEOF     (corrupt record)
3  client closes tab during query       -> ctx.Err() == context.Canceled        -> no response, debug log
4  query exceeds 2 s budget             -> context.DeadlineExceeded             -> 504, maybe retry
5  os.Link on a filesystem without it   -> errors.Is(err, errors.ErrUnsupported) -> fall back to copy

Real scenario: an error-rate SLO that fires because every browser navigation-away logs context canceled at ERROR; a CSV importer that wraps io.EOF and then loops forever because the caller's == io.EOF no longer matches; a storage abstraction whose S3 backend cannot do atomic rename and says so with ErrUnsupported.

ErrorMeaningUsual responseRetry?
io.EOFNormal end of streamStop reading, successNo
io.ErrUnexpectedEOFTruncated inputReport as corrupt inputOnly if the source may resend
context.CanceledCaller/client gave upStop work, no error response, debug-level logNo
context.DeadlineExceededTime budget used up504 / codes.DeadlineExceeded, count itMaybe, with a new budget
errors.ErrUnsupportedOperation not possible hereFallback path or 501No
http.ErrServerClosedListenAndServe returned after ShutdownNormal shutdown, exit 0No
sql.ErrNoRowsQueryRow().Scan found nothingTranslate to your not-foundNo

Fix / how to use it: compare io.EOF with == only on values straight from Read; use errors.Is for the context errors because drivers wrap them; classify in one function (the classify snippet). Context semantics themselves are in context.

defer Must-know ​

In plain words: defer schedules a call to run when the surrounding function returns — by return, by falling off the end, or while a panic unwinds. It is how Go writes finally.

Common misunderstanding: "defer runs at the end of the block (or loop iteration)." It runs at the end of the function. Ten thousand defer f.Close() in a loop hold ten thousand files. A second: "defer fmt.Println(x) prints the final x." Argument evaluation happens at the defer statement; only closures see later changes. A third: "defer is slow." Since Go 1.14, open-coded defers make most uses "almost zero overhead"; a defer inside a loop still falls back to the slower path (measured in the lab: 2.2 ns direct, 3.7 ns with defer, 18 ns with defer in a loop).

Definition: the spec: "Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked. Instead, deferred functions are invoked immediately before the surrounding function returns, in the reverse order they were deferred." Deferred calls run "after any result parameters are set by that return statement but before the function returns to its caller", so a deferred closure can read and change named results. A nil function value panics when invoked, not when deferred.

text
     func Copy(dst io.Writer, r *Resource, src string) (err error)
1    defer func() { if cerr := r.Close(); cerr != nil { err = errors.Join(err, cerr) } }()   // scheduled
2    _, err := io.WriteString(dst, src)  -> io.ErrShortWrite
3    return fmt.Errorf("write report.csv: %w", err)       // named result err is set
4    deferred closure runs: Close() -> "disk full on flush"; err = Join(write err, close err)
5    caller receives both: "write report.csv: short write\nclose report.csv: disk full on flush"

Real scenario: a mutex Unlock that must happen on every path; a resp.Body.Close() that prevents a connection leak (see Ports, Sockets & Connections for CLOSE_WAIT); a tx.Rollback() deferred right after BeginTx (a no-op after Commit); a file writer whose Close error is the only signal that buffered data never reached disk; timing with defer func() { log.Println(time.Since(t)) }() (vet: call to time.Since is not deferred for the wrong form).

PatternCorrectPitfall
Release a lockmu.Lock(); defer mu.Unlock()Deferring before Lock succeeds
Close a file you only readdefer f.Close()Ignoring the error is acceptable for read-only files
Close a file you wroteNamed result + errors.Join(err, f.Close())defer f.Close() loses "disk full"
Transactiontx, err := db.BeginTx(...); if err != nil {...}; defer tx.Rollback()Deferring before the error check (nil tx)
Loop over filesBody in a helper or closure, defer inside itdefer directly in the loop
Timingdefer func() { log.Println(time.Since(t)) }()defer log.Println(time.Since(t)) evaluates now
Modify the resultNamed result in a deferred closureUnnamed results cannot be changed

Fix / how to use it: defer cleanup on the line after acquiring the resource and after its error check; move loop bodies into functions; capture Close errors of writers with a named result. Tested in the defer snippet.

panic Must-know ​

In plain words: panic means "this goroutine cannot continue: something that should be impossible happened." The runtime unwinds the stack, runs defers, and if nobody recovers, the program prints the value and stacks and exits with status 2.

Common misunderstanding: "Panic is for serious errors like a database outage." A database outage is an expected failure; return an error. Effective Go: "real library functions should avoid panic. If the problem can be masked or worked around, it's always better to let things continue to run rather than taking down the whole program." The accepted uses are bugs (broken invariants, "unreachable"), Must* helpers used on constant input at start-up (regexp.MustCompile, template.Must), and initialisation that cannot proceed ("if the library truly cannot set itself up, it might be reasonable to panic").

Definition: the spec: "While executing a function F, an explicit call to panic or a run-time panic terminates the execution of F. Any functions deferred by F are then executed as usual. Next, any deferred functions run by F's caller are run, and so on up to any deferred by the top-level function in the executing goroutine. At that point, the program is terminated and the error condition is reported, including the value of the argument to panic. This termination sequence is called panicking." Run-time panics carry a value of the interface type runtime.Error, which embeds error. Since Go 1.21, panic(nil) becomes *runtime.PanicNilError (old behaviour with GODEBUG=panicnil=1).

Panicking: unwinding one goroutine, frame by framegoroutine 1 stack (top = most recent call)C(): s[3] on len 3runtime panic (runtime.Error)defer c2(), defer c1() run: c2 then c1B(): defer func() { recover() }()recover() returns the panic valueunwinding stops; earlier defers of B runB returns normally (named results kept)A(): continues after B()sees an error, not a panicmain()unwindnormal returnNo recover anywhere?all defers of the goroutine run,then the WHOLE process dies:"panic: ..." + goroutine stacksexit status 2goroutine 18: go worker()its own stack, its own defersmain's recover cannot see itrecover must be deferredat the top of THIS goroutineos.Exit / log.Fatalno unwinding at all:deferred functions do NOT runexit code chosen by caller (1 for Fatal)recover() is nil unless called directlyby a deferred function during a panic.
text
1  main -> A -> B -> C
2  C: s[3] on a slice of length 3            -> panic: runtime error: index out of range [3] with length 3
3  C's defers run (LIFO), C does not return
4  B's defers run; no recover in any of them
5  A's, then main's defers run ("deferred in main ran" is printed)
6  runtime prints the value + "goroutine 1 [running]:" + frames; exit status 2

Real scenario: a switch over an enum with a default: panic(fmt.Sprintf("unknown state %d", s)) that catches a missing case in tests; a regexp.MustCompile on a constant pattern; a config package whose init panics when an embedded schema does not parse; the bad case — a JSON handler that panics on malformed input from users and turns a 400 into a dropped connection.

Panic valueComes fromruntime.Error?Message
Index out of ranges[i], a[i]Yesruntime error: index out of range [3] with length 3
Nil map writem["k"] = v on nil mapYesassignment to entry in nil map
Nil pointer dereferenceu.Name with u == nilYesruntime error: invalid memory address or nil pointer dereference + [signal SIGSEGV ...]
Failed type assertionv.(int) with a stringYes (*runtime.TypeAssertionError)interface conversion: interface {} is string, not int
Integer divide by zeroa / b, b == 0Yesruntime error: integer divide by zero
panic(nil)ExplicitYes (*runtime.PanicNilError, Go 1.21+)runtime error: panic called with nil argument
panic("text") / panic(err)ExplicitNo (unless err is one)the value

Fix / how to use it: panic only for programmer errors and impossible states; never let a panic cross your package's API; return error for anything input-driven.

recover and re-panic Must-know ​

In plain words: recover is the emergency brake for a panic, and it only works if pulled by a deferred function of a frame on the panicking goroutine. Re-panic means "I looked at it and it is not mine: keep crashing."

Common misunderstanding: "I can call recover from a helper logPanic() that my deferred function calls." The spec: "The return value of recover is nil when the goroutine is not panicking or recover was not called directly by a deferred function." defer logPanic() works (the deferred function is logPanic); defer func() { logPanic() }() does not. A second: "after recover, execution continues after the panic line." It continues by returning from the function that deferred the recovering call; the panicking function's remaining code never runs.

Definition: "If D returns normally, without starting a new panic, the panicking sequence stops. In that case, the state of functions called between G and the call to panic is discarded, and normal execution resumes. Any functions deferred by G before D are then run and G's execution terminates by returning to its caller." Use a named result to report the panic as an error. Since Go 1.21, during a panic recover() "is guaranteed not to be nil". Re-panic is calling panic(v) again inside the deferred function for values you do not handle; Effective Go shows it for a parser that recovers only its own Error type ("Will re-panic if not a parse error"). Go 1.25 prints such crashes as panic: PANIC [recovered, repanicked].

text
1  Do(fn) defers D = func() { if v := recover(); v != nil { err = &PanicError{v, debug.Stack()} } }
2  fn: var m map[string]int; m["x"] = 1             -> runtime panic
3  unwinding reaches D; recover() returns the runtime.Error
4  D sets named result err; panicking stops
5  Do returns err to its caller; errors.As(err, &runtime.Error) == true
6  DoStrict variant: D sees runtime.Error -> panic(v) again -> process crashes as before

Real scenario: a worker pool that must not lose 63 workers because one job hit a nil map; a template renderer that recovers its own internal panics and returns an error; a test helper asserting that a function panics; the anti-pattern — defer func() { recover() }() at the top of every function, which turns bugs into silently wrong data.

Where you recoverEffectVerdict
Top of each goroutine you startOne bad job does not kill the processDo it, convert to error, keep the stack
Per HTTP request / per messageRequest fails, server livesnet/http already does it for handlers; add one for a proper 500 body
Inside a package, around a recursive parserInternal panics become an error returnFine, if they never escape
Around every call "just in case"Hides bugs, corrupt state continuesDon't
After runtime.Error you cannot reason aboutState may be half-updatedPrefer re-panic or crash and restart

Fix / how to use it: recover only at boundaries; always capture debug.Stack() inside the deferred function (afterwards the stack is gone); re-panic runtime errors in code where partially updated state is dangerous. Tested in the recover snippet.

Boundaries: goroutines and net/http Must-know ​

In plain words: a panic only unwinds the goroutine it happened in. Each goroutine is its own world: either it recovers its own panics, or the whole process dies. net/http puts a recover around every request for you; nothing does that for goroutines you start.

Common misunderstanding: "My HTTP server recovers panics, so a panic in a goroutine I started from a handler is safe too." That goroutine is outside the server's recover. Another: "since net/http recovers, panicking is a fine way to return 500." The server only logs and drops the connection (HTTP/1) or resets the stream (HTTP/2); the client sees a network error, not a 500.

Definition: the http.Handler doc: "If ServeHTTP panics, the server (the caller of ServeHTTP) assumes that the effect of the panic was isolated to the active request. It recovers the panic, logs a stack trace to the server error log, and either closes the network connection or sends an HTTP/2 RST_STREAM". The server's conn.serve defers a recover that logs http: panic serving <addr>: <value> with a 64 KiB stack. http.ErrAbortHandler is "a sentinel panic value to abort a handler" that "suppresses logging of a stack trace."

text
1  request A -> handler panics "handler bug"
2  net/http's deferred recover in conn.serve: logs "http: panic serving 127.0.0.1:...: handler bug" + stack
3  connection closed; client gets EOF / "connection reset"; server keeps running
4  request B on a new connection -> 200 "ok"
5  handler starts go worker(); worker panics -> no recover on that goroutine -> process exits, status 2

Real scenario: a webhook handler that fans out to go notify(...); one malformed payload panics inside notify and restarts the pod, dropping every in-flight request; an image resize worker pool where one corrupt PNG kills all workers; an API that returns proper JSON 500s because a recover middleware wraps the router.

BoundaryRecovers by default?What you add
net/http handlerYes: logs, closes connection / RST_STREAMRecover middleware writing a Problem Details 500; re-panic http.ErrAbortHandler
Goroutine you start with goNodefer + recover at its top, deliver an error on a channel
errgroup.Group.GoNo: a panic in f is neither returned by Wait nor propagated; it crashes the process (the source explains why)Your own recover in the function you pass
gRPC-Go server handlerNo by defaultA recovery interceptor (see gRPC & Protobuf in Go)
testing test functionThe test fails and the binary stopsNothing; use t.Fatal for expected failures
init()NoNothing: a failed init should stop the program

Fix / how to use it: every go statement you write in long-running code starts with a deferred recover that turns the panic into an error with a stack; the HTTP edge has one recover middleware (the full middleware chain is in Middlewares). Tested in the HTTP boundary snippet including TestServerSurvivesPanic.

os.Exit, log.Fatal and exit codes Important ​

In plain words: os.Exit ends the process immediately with a number for the shell. Nothing else runs: no defers, no flushing of buffered writers, no cleanup. log.Fatal is "print, then os.Exit(1)".

Common misunderstanding: "log.Fatal is a graceful shutdown." It skips every deferred call, so a deferred tx.Rollback(), file.Close() or tracer.Shutdown() never runs. A second: "a panic and os.Exit(1) are the same to the shell." An unrecovered panic exits with status 2 and prints stacks; log.Fatal exits 1.

Definition: os.Exit: "Conventionally, code zero indicates success, non-zero an error. The program terminates immediately; deferred functions are not run. For portability, the status code should be in the range [0, 125]." log.Fatal "is equivalent to Print followed by a call to os.Exit(1)." The main pattern: func main() { os.Exit(run(...)) } where run returns a code (or an error) and holds all the defers. Shells report 128+N for death by signal N (130 for SIGINT).

text
1  main() calls run(ctx, args, stdout, stderr)
2  run: defer cleanup()  ...  work() -> "workers=0: invalid configuration"
3  run prints "error: ..." once to stderr, returns 3; cleanup() runs ("cleanup ran")
4  main: os.Exit(3)                                  -> shell: $? == 3
5  same program with log.Fatal inside work()         -> "cleanup ran" never printed, $? == 1

Real scenario: a migration CLI that exits 0 after failing because it printed the error and forgot to return a code (CI marks the deploy green); a Kubernetes Job whose exit status decides retries (backoffLimit); a CLI that exits 2 on bad flags (the flag package's convention) so wrappers can tell usage errors from runtime failures.

Exit codeConventionProduced by
0Successreturn from main, os.Exit(0), -h with flag.ContinueOnError handled
1General failurelog.Fatal, os.Exit(1), most tools
2Usage error (Go flag); also unrecovered panic and fatal error:flag.ExitOnError, runtime crash
3–125Program-specific (document them)os.Exit(n)
126 / 127Shell: not executable / not foundThe shell, not your program
128+NKilled by signal N (130 = SIGINT, 137 = SIGKILL, 143 = SIGTERM)Shell / container runtime

Fix / how to use it: call os.Exit in exactly one place, main, with nothing deferred in main itself; keep log.Fatal out of libraries and out of code that holds resources. Tested in the exit code snippet; signals are in OS Processes, Signals.

Stack traces: debug.Stack and the pkg/errors history Good to know ​

In plain words: Go errors do not carry a stack trace; the chain of wrap messages is the trace. When you do need frames — for a recovered panic — you capture them yourself with runtime/debug.Stack().

Common misunderstanding: "I should attach a stack trace to every error." That was the pkg/errors approach; it costs a stack walk per error and duplicates what good messages give. The standard library chose messages. Capture stacks only where context is otherwise lost: recovered panics and, at most, the boundary that creates an unexpected internal error.

Definition: debug.Stack() "returns a formatted stack trace of the goroutine that calls it. It calls runtime.Stack with a large enough buffer to capture the entire trace." It must be called inside the deferred function to see the panicking frames. GOTRACEBACK controls crash output (none, single default, all, system, crash). github.com/pkg/errors (Wrap, Wrapf, Cause, %+v printing the stack) predates Go 1.13 and is in maintenance mode.

text
1  defer func() { v := recover(); stack := debug.Stack(); ... }()   // frames still present
2  goroutine 1 [running]:
3  runtime/debug.Stack()
4  	runtime/debug/stack.go:26 +0x64
5  main.main()
6  	academy/errors-panic-recover-defer/labpanic/main.go:54 +0x19c

Real scenario: a worker logs a recovered panic with its stack as one structured field; a team migrating from pkg/errors replaces errors.Wrap(err, "x") with fmt.Errorf("x: %w", err) and errors.Cause with errors.Is/As; production builds use -trimpath so stacks do not reveal build-machine paths.

ApproachStack?CostToday
Wrap messages (%w)No, a readable chainAllocation per wrapStandard
pkg/errors.WrapYes, at creationStack walk per errorMaintenance mode; migrate
debug.Stack() in recoverYes, of the panicking goroutineOnly on panicStandard for boundaries
GOTRACEBACK=allAll goroutines on crashCrash onlyUseful in staging

Fix / how to use it: messages for errors, debug.Stack() for panics, -trimpath for builds; see Observability for shipping them.

Linters: errcheck, errorlint, wrapcheck and go vet Good to know ​

In plain words: the compiler lets you ignore a returned error; linters do not.

Common misunderstanding: "go vet checks that I handle errors." Vet checks %w operands, errors.As targets and deferred time.Since, but not ignored errors. That is errcheck ("errcheck checks that you checked errors"); golangci-lint help linters shows whether your configuration enables it.

Definition: errcheck reports unchecked error results. errorlint "can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13": err == ErrFoo (should be errors.Is), err.(*MyError) (should be errors.As), and with -errorf a %v that should be %w. wrapcheck checks "that errors from external packages are wrapped" (message: error returned from external package is unwrapped). All three run inside golangci-lint (configuration in Project Layout, golangci-lint).

text
1  f.Close()                      -> errcheck: reports the unchecked call f.Close()
2  if err == sql.ErrNoRows        -> errorlint: comparing with == will fail on wrapped errors
3  return User{}, err             -> wrapcheck: error returned from external package is unwrapped
4  fmt.Errorf("x: %w", "s")       -> go vet: fmt.Errorf format %w has arg "s" of wrong type string

Real scenario: a PR that adds defer rows.Close() without rows.Err() (errcheck does not catch rows.Err() absence; review does); a codebase-wide migration from == to errors.Is driven by errorlint -fix; wrapcheck with an ignorePackageGlobs list for your own module so it only fires on third-party errors.

ToolCatchesMisses
go vetBad %w operand, errors.As non-pointer target, deferred time.Since, %w on **E (1.27)Ignored errors
errcheck_ = f()-less ignored errors, unchecked CloseSemantics: whether you handled it well
errorlint==, type assertions, type switches on errors; %v vs %w with -errorfWhether wrapping leaks internals
wrapcheckReturning third-party errors without contextWhether context is useful
ReviewHandle once, leaks, panics across APIs—

Fix / how to use it: enable errcheck, errorlint, wrapcheck and vet in CI; exclude read-only Close with a comment rather than a blanket rule.

Go ​

Before ​

A store that compiles and passes a happy-path test, but flattens the cause with %v, matches errors by string, logs and returns, and panics on bad data.

go
// Package before shows error handling that compiles, passes a happy-path test
// and still hurts in production: string matching, lost causes, log-and-return
// at every layer, and panic used for an ordinary failure.
package before

import (
	"database/sql"
	"fmt"
	"log"
	"strings"
)

type Order struct {
	ID     string
	Amount int64
}

type Store struct {
	rows map[string]Order
}

func NewStore(rows map[string]Order) *Store { return &Store{rows: rows} }

func (s *Store) Find(id string) (Order, error) {
	o, ok := s.rows[id]
	if !ok {
		// The cause is flattened to text; callers can only compare strings.
		return Order{}, fmt.Errorf("order %s: %v", id, sql.ErrNoRows)
	}
	return o, nil
}

// Load logs AND returns: the same failure is now reported once per layer.
func (s *Store) Load(id string) (Order, error) {
	o, err := s.Find(id)
	if err != nil {
		log.Printf("load failed: %v", err)
		return Order{}, err
	}
	if o.Amount < 0 {
		// A data problem is not a programmer bug, but this crashes the process.
		panic("negative amount for order " + id)
	}
	return o, nil
}

// IsNotFound depends on the exact wording of a message in another package.
func IsNotFound(err error) bool {
	return err != nil && strings.Contains(err.Error(), "no rows in result set")
}

After ​

The same store with one sentinel (ErrNotFound), one error type with fields (*InvalidOrderError), context added once with %w, and a single Status function as the boundary decision.

go
// Package after is the same store with errors designed as part of the API:
// one sentinel for "not found", one error type with fields for invalid data,
// context added once per layer with %w, and no logging below the boundary.
package after

import (
	"errors"
	"fmt"
)

// ErrNotFound is the only sentinel this package promises to callers.
var ErrNotFound = errors.New("order not found")

// InvalidOrderError carries the fields a caller needs to build a response.
type InvalidOrderError struct {
	OrderID string
	Field   string
	Reason  string
}

func (e *InvalidOrderError) Error() string {
	return fmt.Sprintf("order %s: invalid %s: %s", e.OrderID, e.Field, e.Reason)
}

type Order struct {
	ID     string
	Amount int64
}

// Repo is the storage port; a real implementation wraps database/sql or pgx.
type Repo interface {
	Get(id string) (Order, error)
}

type Service struct{ repo Repo }

func NewService(r Repo) *Service { return &Service{repo: r} }

// Load adds context ("load order o-1") and keeps the cause inspectable.
func (s *Service) Load(id string) (Order, error) {
	o, err := s.repo.Get(id)
	if err != nil {
		return Order{}, fmt.Errorf("load order %s: %w", id, err)
	}
	if o.Amount < 0 {
		return Order{}, &InvalidOrderError{OrderID: id, Field: "amount", Reason: "must not be negative"}
	}
	return o, nil
}

// MapRepo is an in-memory Repo that translates its own "missing key" into
// the package sentinel, so callers never see storage details.
type MapRepo map[string]Order

func (m MapRepo) Get(id string) (Order, error) {
	o, ok := m[id]
	if !ok {
		return Order{}, ErrNotFound
	}
	return o, nil
}

// Status is what an HTTP or CLI boundary does: inspect once, decide once.
func Status(err error) int {
	var invalid *InvalidOrderError
	switch {
	case err == nil:
		return 200
	case errors.Is(err, ErrNotFound):
		return 404
	case errors.As(err, &invalid):
		return 422
	default:
		return 500
	}
}

The Go angle ​

The standard library is the style guide. os returns *fs.PathError{Op, Path, Err} that wraps syscall errors, so errors.Is(err, fs.ErrNotExist) works across platforms. database/sql exposes a handful of sentinels callers branch on (sql.ErrNoRows, sql.ErrTxDone, sql.ErrConnDone) and otherwise passes driver errors through; pgx exposes *pgconn.PgError with Code (SQLSTATE) for errors.As (see database/sql & pgx). net errors satisfy net.Error with Timeout(), and since Go 1.23 *net.DNSError wraps context errors. encoding/json returns *json.SyntaxError and *json.UnmarshalTypeError. net/http documents http.ErrServerClosed as the normal result of Shutdown and recovers handler panics. bufio.Scanner and io.ReadAll absorb io.EOF so callers see nil at the end. text/template's parser and encoding/json's encoder use internal panics that they recover into errors, and template.Must/regexp.MustCompile exist for constant input. The pattern is consistent: errors as values, few sentinels, typed errors where data matters, panics never across the API.

Mechanics ​

Runtime and vet messages, verbatim Must-know ​

Captured from Go 1.27.4 on macOS arm64 with the lab program (built with -trimpath) and go vet.

TriggerExact textExit status
s[i], i == len(s) == 3panic: runtime error: index out of range [3] with length 32
Write to nil mappanic: assignment to entry in nil map2
Nil pointer field readpanic: runtime error: invalid memory address or nil pointer dereference then [signal SIGSEGV: segmentation violation code=0x2 addr=0x0 pc=...]2
v.(int) on a stringpanic: interface conversion: interface {} is string, not int2
panic(errors.New("config: missing DATABASE_URL"))panic: config: missing DATABASE_URL2
Recover then panic(v) again (Go 1.25+)panic: PANIC [recovered, repanicked]2
Panic in a goroutine, main has a recoverpanic: worker died ... created by main.main in goroutine 12
All goroutines blockedfatal error: all goroutines are asleep - deadlock!2
os.Exit(3)nothing printed; defers skipped3
log.Fatal("cannot start: port in use")2026/11/26 10:22:31 cannot start: port in use; defers skipped1
http.Handler panicsserver log: http: panic serving 127.0.0.1:54321: handler bug + stack(server lives)
fmt.Errorf("x: %w", nil)x: %!w(<nil>)—
fmt.Errorf("x: %w", "str") at run timex: %!w(string=str)—
vet, %w with a stringfmt.Errorf format %w has arg "not an error" of wrong type stringvet fails
vet, %w with **MyErrfmt.Errorf format %w has arg &e of wrong type **vetdemo.MyErrvet fails
vet, errors.As(err, pe) with a valuesecond argument to errors.As must be a non-nil pointer to either a type that implements error, or to any interface typevet fails
vet, defer log.Println(time.Since(t))call to time.Since is not deferredvet fails
ctx.Err() after cancel / deadlinecontext canceled / context deadline exceeded—

How Is and As walk the tree ​

errors.Is(err, target) loops: if err == target (when comparable) or err has Is(error) bool returning true, done; otherwise it calls Unwrap() error and continues, or for Unwrap() []error recurses into each child in order. errors.As(err, &target) does the same with "is assignable to the target's element type" or an As(any) bool method, and panics if target is not a non-nil pointer to an interface or a type implementing error (vet catches it first). A cycle in Unwrap would loop forever, so never make an error unwrap to itself. The cost is linear in the size of the tree; a few nodes in practice.

What a panic does to the stack ​

text
1  panic(v) or runtime fault in C
2  runtime creates a _panic record on the goroutine, value v
3  runs C's deferred calls, newest first; each may call recover()
4  none recovered -> pop C, run B's defers, then A's, then main's (for goroutine 1)
5  reached the top of the goroutine -> print "panic: " + v (+ " [recovered]" annotations), then tracebacks
6  exit(2)  -- other goroutines are not unwound; their defers never run

The last line matters: when one goroutine crashes the process, defers in other goroutines do not run. Only the panicking goroutine unwinds. Likewise os.Exit unwinds nothing anywhere.

What defer costs ​

Go 1.13 made "most uses of defer" 30% faster; Go 1.14 introduced open-coded defers, making them cost "almost zero overhead compared to calling the deferred function directly". Open coding means the compiler emits the deferred calls inline at each exit; it can only do that for defers it can count statically, so a defer inside a loop still goes through the runtime's slower path. Our benchmark on an Apple M4 Pro, Go 1.27.4, go test -bench . -count 3 ./deferorder:

Benchmarkns/op (3 runs)What it shows
BenchmarkUnlockDirect2.194, 2.164, 2.195Lock + increment + Unlock, no defer
BenchmarkUnlockDefer3.720, 3.705, 3.700Same with defer mu.Unlock(): ~1.5 ns more
BenchmarkUnlockDeferInLoop18.13, 18.10, 17.97defer inside a for: falls off the open-coded path

The lesson is not "avoid defer" (1.5 ns is nothing next to a syscall) but "never defer in a loop", which is wrong for resource reasons anyway.

Error values across APIs: gRPC status and Problem Details ​

An error is an in-process value; it does not cross a network. At an RPC boundary you translate it into the protocol's error model, and on the other side back into a value.

Domain errorHTTP status + RFC 9457 typegRPC codes.*Exit code (CLI)
ErrNotFound404, /problems/not-foundNotFound1 or program-specific
*ValidationError422 (or 400), /problems/validation + fieldInvalidArgument2 for flag/usage errors
ErrConflict / version mismatch409Aborted or AlreadyExists—
Precondition (state machine)409 / 412FailedPrecondition—
context.DeadlineExceeded504 (gateway)DeadlineExceeded1
context.Canceledno response (client gone); log 499-styleCanceled130 on SIGINT
errors.ErrUnsupported501Unimplemented—
Rate limited429 + Retry-AfterResourceExhausted—
Anything else500, about:blank, no internalsInternal (or Unknown)1

RFC 9457 (which obsoletes RFC 7807) defines a "problem detail" "to carry machine-readable details of errors in HTTP response content", media type application/problem+json, members type, title, status, detail, instance. In gRPC-Go, status.Error(codes.NotFound, "order not found") builds the error; on the client status.FromError(err) recovers it, and also works "if err wraps a type satisfying" GRPCStatus() *Status; for anything else it returns codes.Unknown. status.Code(err) returns the code or codes.Unknown. Never put err.Error() of an internal error into detail or the gRPC message: it can contain SQL, hostnames or file paths.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Caller cannot tell not-found from failureSentinel + %wErrNotFound, errors.IsSimple, cheapSentinel is permanent API
Caller needs details (field, path, code)Error type*ValidationError, errors.AsStructured responsesType and fields are API
Many failures at onceerrors.Join / Unwrap() []errorCollect, join, inspectNothing lostMulti-line text
Driver errors leak through the APITranslate at the boundary%v or own sentinelFreedom to change storageCallers lose detail (by design)
Same failure logged N timesHandle onceWrap below, log at boundaryOne line, full contextDiscipline; review
Close error on written files lostNamed result + deferred errors.JoinSee CopyNo silent data lossSlightly longer code
Files/locks held until function endNo defer in loopsClosure per iterationBounded resourcesOne more function
Panic in a goroutine kills the serviceRecover at goroutine toprecoverboundary.GoProcess survivesMust still fix the bug
Handler panic gives client a resetRecover middlewareProblem Details 500Proper response, one logDoesn't fix half-updated state
context canceled floods error logsClassify signalsclassify.OfHonest error ratesNeeds one shared helper
CLI exits 0 after failurerun() int + one os.ExitexitcodeDefers run, correct $?—
err == x misses wrapped errorserrors.Is/As + errorlintLinter in CIMechanical fixSome false positives

Building and inspecting the error tree ​

Single %w, two %w, errors.Join, a ValidationErrors type with Unwrap() []error, a custom Is that matches status classes, and the typed-nil trap, each with a test.

go
// Package wrapping shows the error tree: single %w, several %w (Go 1.20),
// errors.Join, a custom Unwrap() []error, a custom Is method, and the
// typed-nil trap that makes a "nil" error non-nil.
package wrapping

import (
	"errors"
	"fmt"
	"strings"
)

var (
	ErrTimeout  = errors.New("timeout")
	ErrConflict = errors.New("conflict")
)

// Wrap1 wraps exactly one cause.
func Wrap1(op string, err error) error { return fmt.Errorf("%s: %w", op, err) }

// Wrap2 wraps two causes at once; Unwrap() on the result returns []error.
func Wrap2(op string, a, b error) error { return fmt.Errorf("%s: %w; %w", op, a, b) }

// FieldError is one validation failure.
type FieldError struct{ Field, Msg string }

func (e *FieldError) Error() string { return e.Field + ": " + e.Msg }

// ValidationErrors collects many FieldErrors and exposes them as a tree.
type ValidationErrors []*FieldError

func (v ValidationErrors) Error() string {
	parts := make([]string, len(v))
	for i, e := range v {
		parts[i] = e.Error()
	}
	return "validation failed: " + strings.Join(parts, "; ")
}

func (v ValidationErrors) Unwrap() []error {
	out := make([]error, len(v))
	for i, e := range v {
		out[i] = e
	}
	return out
}

// Validate returns nil (a true nil interface) when everything is fine.
func Validate(name string, qty int) error {
	var errs ValidationErrors
	if name == "" {
		errs = append(errs, &FieldError{"name", "required"})
	}
	if qty <= 0 {
		errs = append(errs, &FieldError{"qty", "must be positive"})
	}
	if len(errs) == 0 {
		return nil
	}
	return errs
}

// ValidateBuggy returns a typed nil: the interface holds (*ValidationErrors)(nil).
func ValidateBuggy(name string) error {
	var errs *ValidationErrors
	if name == "" {
		errs = &ValidationErrors{{"name", "required"}}
	}
	return errs // non-nil interface even when errs == nil
}

// HTTPStatusError matches any target with the same status class via Is.
type HTTPStatusError struct{ Code int }

func (e *HTTPStatusError) Error() string { return fmt.Sprintf("http status %d", e.Code) }

// Is lets errors.Is(err, &HTTPStatusError{Code: 500}) match any 5xx.
func (e *HTTPStatusError) Is(target error) bool {
	t, ok := target.(*HTTPStatusError)
	return ok && t.Code/100 == e.Code/100
}

// CloseAll closes every closer and joins every failure; nil if all succeed.
func CloseAll(closers ...func() error) error {
	var errs []error
	for _, c := range closers {
		errs = append(errs, c()) // errors.Join drops nil values
	}
	return errors.Join(errs...)
}

Opaque errors and behaviour at a package boundary ​

LookupUser translates sql.ErrNoRows into its own sentinel, keeps "temporary" as behaviour while hiding the driver type, and uses %v for everything else. The test proves the driver error is not reachable with errors.Is.

go
// Package opaque shows the two boundary rules from the Go blog and Dave
// Cheney: assert errors for behaviour, not type, and do not wrap a cause you
// are not willing to support as part of your API.
package opaque

import (
	"database/sql"
	"errors"
	"fmt"
)

// temporary is the behaviour callers care about; no import of our types needed.
type temporary interface{ Temporary() bool }

// IsTemporary reports whether any error in the tree says it may succeed later.
func IsTemporary(err error) bool {
	var t temporary
	return errors.As(err, &t) && t.Temporary()
}

type lockTimeout struct{ table string }

func (e lockTimeout) Error() string   { return "lock timeout on " + e.table }
func (e lockTimeout) Temporary() bool { return true }

// ErrUserNotFound is the stable, public meaning; sql.ErrNoRows is a detail.
var ErrUserNotFound = errors.New("user not found")

type DB interface {
	QueryUser(id int) (string, error)
}

// LookupUser translates storage errors at the package boundary.
func LookupUser(db DB, id int) (string, error) {
	name, err := db.QueryUser(id)
	switch {
	case err == nil:
		return name, nil
	case errors.Is(err, sql.ErrNoRows):
		return "", fmt.Errorf("lookup user %d: %w", id, ErrUserNotFound)
	case IsTemporary(err):
		// Keep the behaviour visible, but hide the driver type: %w on our own wrapper.
		return "", fmt.Errorf("lookup user %d: %w", id, retryable{err})
	default:
		// %v: the text survives for logs, the driver error is not part of our API.
		return "", fmt.Errorf("lookup user %d: %v", id, err)
	}
}

type retryable struct{ cause error }

func (r retryable) Error() string   { return r.cause.Error() }
func (r retryable) Temporary() bool { return true }

defer order, argument evaluation and Close errors ​

go
// Package deferorder pins down defer semantics: LIFO order, arguments
// evaluated at the defer statement, named results changed after return,
// the defer-in-a-loop trap, and capturing a Close error without losing
// the primary error.
package deferorder

import (
	"errors"
	"fmt"
	"io"
	"strings"
)

// Order records the order deferred calls run in.
func Order() []string {
	var log []string
	func() {
		for i := 0; i < 3; i++ {
			defer func(n int) { log = append(log, fmt.Sprint("defer ", n)) }(i)
		}
		log = append(log, "body")
	}()
	return log // body, defer 2, defer 1, defer 0
}

// ArgsNow shows that arguments are evaluated when defer runs, not later.
func ArgsNow() (atDefer, atReturn string) {
	var b strings.Builder
	func() {
		x := "first"
		defer fmt.Fprint(&b, x) // x copied now
		defer func() { atReturn = x }()
		x = "second"
	}()
	return b.String(), atReturn // "first", "second"
}

// Triple returns 3*n by changing the named result after return sets it.
func Triple(n int) (result int) {
	defer func() { result *= 3 }()
	return n
}

// Resource is a closer whose Close can fail.
type Resource struct {
	Name     string
	CloseErr error
	closed   *[]string
}

func (r *Resource) Close() error {
	*r.closed = append(*r.closed, r.Name)
	return r.CloseErr
}

// OpenAllLeaky defers inside a loop: nothing closes until the function ends,
// so with 10 000 files you hold 10 000 descriptors at once.
func OpenAllLeaky(names []string, closed *[]string, during func(open int)) {
	open := 0
	for _, n := range names {
		r := &Resource{Name: n, closed: closed}
		open++
		defer r.Close() //nolint:errcheck // the trap shown here is the loop, not the ignored error
		during(open)
	}
}

// OpenAllScoped closes each resource at the end of its own iteration.
func OpenAllScoped(names []string, closed *[]string, during func(open int)) {
	open := 0
	for _, n := range names {
		func() {
			r := &Resource{Name: n, closed: closed}
			open++
			defer func() { _ = r.Close(); open-- }()
			during(open)
		}()
	}
}

// Copy writes src to a resource and reports BOTH a write error and a Close
// error, using a named result and errors.Join in the deferred call.
func Copy(dst io.Writer, r *Resource, src string) (err error) {
	defer func() {
		if cerr := r.Close(); cerr != nil {
			err = errors.Join(err, fmt.Errorf("close %s: %w", r.Name, cerr))
		}
	}()
	if _, err := io.WriteString(dst, src); err != nil {
		return fmt.Errorf("write %s: %w", r.Name, err)
	}
	return nil
}

Converting panics to errors, re-panicking bugs ​

Do recovers and keeps the stack; DoStrict re-panics runtime.Error; Go gives a goroutine its own boundary; IndirectRecover proves that a recover in a helper does nothing.

go
// Package recoverboundary converts panics into errors at the two places Go
// does not do it for you: the top of a goroutine you start, and any function
// boundary you choose to protect. It keeps the stack, keeps runtime.Error
// inspectable, and can re-panic for programmer bugs.
package recoverboundary

import (
	"errors"
	"fmt"
	"runtime"
	"runtime/debug"
)

// PanicError is a recovered panic turned into an ordinary error value.
type PanicError struct {
	Value any    // what was passed to panic
	Stack []byte // debug.Stack() captured inside the deferred function
}

func (p *PanicError) Error() string { return fmt.Sprintf("panic: %v", p.Value) }

// Unwrap exposes the panic value when it is itself an error, so
// errors.As(err, &runtimeErr) works for index-out-of-range, nil map, etc.
func (p *PanicError) Unwrap() error {
	if err, ok := p.Value.(error); ok {
		return err
	}
	return nil
}

// Do runs fn and returns its error, or a *PanicError if fn panicked.
func Do(fn func() error) (err error) {
	defer func() {
		if v := recover(); v != nil {
			err = &PanicError{Value: v, Stack: debug.Stack()}
		}
	}()
	return fn()
}

// DoStrict recovers panics raised on purpose but re-panics runtime errors:
// a nil dereference is a bug and should crash loudly in tests and CI.
func DoStrict(fn func() error) (err error) {
	defer func() {
		v := recover()
		if v == nil {
			return
		}
		if re, ok := v.(runtime.Error); ok {
			panic(re) // re-panic: Go 1.25+ prints "[recovered, repanicked]"
		}
		err = &PanicError{Value: v, Stack: debug.Stack()}
	}()
	return fn()
}

// Go starts fn in a goroutine and delivers exactly one result on the channel.
// Without the deferred recover a panic here would kill the whole process,
// whatever recover the caller has on its own goroutine.
func Go(fn func() error) <-chan error {
	out := make(chan error, 1)
	go func() {
		out <- Do(fn)
	}()
	return out
}

// helperRecover is NOT called directly by the deferred function, so its
// recover returns nil and the panic keeps unwinding.
func helperRecover() any { return recover() }

// IndirectRecover demonstrates that rule; it always panics through.
func IndirectRecover(fn func()) (got any) {
	defer func() { got = helperRecover() }()
	fn()
	return nil
}

// IsRuntime reports whether err came from a runtime panic.
func IsRuntime(err error) bool {
	var re runtime.Error
	return errors.As(err, &re)
}
go
package recoverboundary

import (
	"bytes"
	"errors"
	"runtime"
	"strings"
	"testing"
)

var errBoom = errors.New("boom")

func TestDoReturnsErrorsUnchanged(t *testing.T) {
	if err := Do(func() error { return errBoom }); err != errBoom {
		t.Fatalf("got %v", err)
	}
}

func TestDoConvertsRuntimePanic(t *testing.T) {
	err := Do(func() error {
		var s []int
		_ = s[3] // index out of range
		return nil
	})
	var pe *PanicError
	if !errors.As(err, &pe) {
		t.Fatalf("want *PanicError, got %T", err)
	}
	if !IsRuntime(err) {
		t.Fatal("runtime.Error must be reachable through Unwrap")
	}
	if got := err.Error(); got != "panic: runtime error: index out of range [3] with length 0" {
		t.Fatalf("message: %q", got)
	}
	if !bytes.Contains(pe.Stack, []byte("goroutine ")) {
		t.Fatal("stack trace missing")
	}
}

func TestPanicNil(t *testing.T) {
	err := Do(func() error { panic(nil) })
	var pn *runtime.PanicNilError
	if !errors.As(err, &pn) {
		t.Fatalf("Go 1.21+: panic(nil) becomes *runtime.PanicNilError, got %v", err)
	}
}

func TestDoStrictRepanicsRuntimeErrors(t *testing.T) {
	err := DoStrict(func() error { panic("bad config") })
	if err == nil || !strings.Contains(err.Error(), "bad config") {
		t.Fatalf("deliberate panic should become an error: %v", err)
	}
	defer func() {
		v := recover()
		if _, ok := v.(runtime.Error); !ok {
			t.Fatalf("want re-panicked runtime.Error, got %v", v)
		}
	}()
	_ = DoStrict(func() error {
		var m map[string]int
		m["x"] = 1 // assignment to entry in nil map
		return nil
	})
	t.Fatal("unreachable: DoStrict must re-panic")
}

func TestGoroutineBoundary(t *testing.T) {
	err := <-Go(func() error { panic("worker exploded") })
	var pe *PanicError
	if !errors.As(err, &pe) || pe.Value != "worker exploded" {
		t.Fatalf("got %v", err)
	}
}

func TestRecoverMustBeCalledDirectly(t *testing.T) {
	defer func() {
		if v := recover(); v != "through" {
			t.Fatalf("panic should pass the indirect recover, got %v", v)
		}
	}()
	IndirectRecover(func() { panic("through") })
	t.Fatal("unreachable")
}

The HTTP boundary: one adapter, Problem Details, recover ​

Handlers return error; Handle maps the tree to RFC 9457 bodies, logs exactly once, treats context.Canceled as quiet; Recover writes a 500 without leaking the panic text and re-panics http.ErrAbortHandler. The test file also shows net/http's own per-request recover keeping the server alive.

go
// Package httpboundary is where errors stop travelling and become a response:
// handlers return error, one adapter maps the error tree to an RFC 9457
// Problem Details body, logs it once, and a recover wrapper turns a panic
// into a 500 without leaking internals.
package httpboundary

import (
	"context"
	"encoding/json"
	"errors"
	"log/slog"
	"net/http"
	"runtime/debug"
)

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

// ValidationError carries field details that are safe to show to clients.
type ValidationError struct{ Field, Reason string }

func (e *ValidationError) Error() string { return e.Field + ": " + e.Reason }

// Problem is the RFC 9457 body (application/problem+json).
type Problem struct {
	Type     string `json:"type"`
	Title    string `json:"title"`
	Status   int    `json:"status"`
	Detail   string `json:"detail,omitempty"`
	Instance string `json:"instance,omitempty"`
}

// HandlerFunc is a handler that returns its failure instead of writing it.
type HandlerFunc func(w http.ResponseWriter, r *http.Request) error

// Handle adapts a HandlerFunc. It is the single place that inspects the error,
// picks a status, writes a body, and logs. Lower layers only wrap and return.
func Handle(log *slog.Logger, h HandlerFunc) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		err := h(w, r)
		if err == nil {
			return
		}
		p := toProblem(err)
		p.Instance = r.URL.Path
		if errors.Is(err, context.Canceled) {
			// The client went away; nobody reads the response. Log at debug only.
			log.Debug("request canceled", "path", r.URL.Path)
			return
		}
		level := slog.LevelInfo
		if p.Status >= 500 {
			level = slog.LevelError
		}
		log.Log(r.Context(), level, "request failed", "status", p.Status, "err", err)
		writeProblem(w, p)
	})
}

func toProblem(err error) Problem {
	var ve *ValidationError
	switch {
	case errors.As(err, &ve):
		return Problem{Type: "/problems/validation", Title: "Invalid request", Status: http.StatusUnprocessableEntity, Detail: ve.Error()}
	case errors.Is(err, ErrNotFound):
		return Problem{Type: "/problems/not-found", Title: "Not found", Status: http.StatusNotFound}
	case errors.Is(err, ErrConflict):
		return Problem{Type: "/problems/conflict", Title: "Conflict", Status: http.StatusConflict}
	case errors.Is(err, context.DeadlineExceeded):
		return Problem{Type: "/problems/timeout", Title: "Upstream timeout", Status: http.StatusGatewayTimeout}
	case errors.Is(err, errors.ErrUnsupported):
		return Problem{Type: "/problems/unsupported", Title: "Not implemented", Status: http.StatusNotImplemented}
	default:
		// Never put err.Error() here: it may contain SQL, hostnames or file paths.
		return Problem{Type: "about:blank", Title: "Internal Server Error", Status: http.StatusInternalServerError}
	}
}

func writeProblem(w http.ResponseWriter, p Problem) {
	w.Header().Set("Content-Type", "application/problem+json")
	w.WriteHeader(p.Status)
	_ = json.NewEncoder(w).Encode(p) // the client may be gone; nothing useful to do
}

// Recover turns a panic in next into a logged 500. net/http would recover it
// too, but it only logs and drops the connection; this writes a proper body.
// http.ErrAbortHandler is re-panicked so net/http can abort silently.
func Recover(log *slog.Logger, 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 {
				panic(v)
			}
			log.Error("panic serving request", "path", r.URL.Path, "panic", v, "stack", string(debug.Stack()))
			writeProblem(w, Problem{Type: "about:blank", Title: "Internal Server Error", Status: http.StatusInternalServerError, Instance: r.URL.Path})
		}()
		next.ServeHTTP(w, r)
	})
}

Classifying errors: EOF, cancel, timeout, unsupported ​

go
// Package classify turns an error tree into the one decision a caller has to
// make: stop normally, give up quietly, retry, or fail. It also shows io.EOF
// used as a signal rather than a failure.
package classify

import (
	"bufio"
	"context"
	"errors"
	"fmt"
	"io"
	"net"
	"strconv"
)

type Kind int

const (
	OK          Kind = iota
	EndOfStream      // io.EOF: the normal end of input
	Canceled         // the caller gave up: context.Canceled
	Timeout          // a deadline passed: context.DeadlineExceeded or net timeout
	Unsupported      // errors.ErrUnsupported: do not retry, pick another path
	Permanent        // everything else: report it
)

func (k Kind) String() string {
	return [...]string{"ok", "end-of-stream", "canceled", "timeout", "unsupported", "permanent"}[k]
}

// Of classifies err. Order matters: check the specific meanings first.
func Of(err error) Kind {
	var ne net.Error
	switch {
	case err == nil:
		return OK
	case err == io.EOF: // io.EOF is returned unwrapped by contract
		return EndOfStream
	case errors.Is(err, context.Canceled):
		return Canceled
	case errors.Is(err, context.DeadlineExceeded):
		return Timeout
	case errors.As(err, &ne) && ne.Timeout():
		return Timeout
	case errors.Is(err, errors.ErrUnsupported):
		return Unsupported
	default:
		return Permanent
	}
}

// Retryable reports whether a retry can change the outcome.
func Retryable(err error) bool { return Of(err) == Timeout }

// SumLines reads integers, one per line. Reaching the end is success;
// a bad line is an error with its line number; a read failure is wrapped.
func SumLines(r io.Reader) (int, error) {
	sc := bufio.NewScanner(r) // Scanner hides io.EOF: Err() returns nil at the end
	sum, line := 0, 0
	for sc.Scan() {
		line++
		n, err := strconv.Atoi(sc.Text())
		if err != nil {
			return 0, fmt.Errorf("line %d: %w", line, err)
		}
		sum += n
	}
	if err := sc.Err(); err != nil {
		return 0, fmt.Errorf("read numbers: %w", err)
	}
	return sum, nil
}

// ReadRecord reads exactly n bytes. Zero bytes then EOF is a clean end;
// a partial record is io.ErrUnexpectedEOF, which IS an error.
func ReadRecord(r io.Reader, n int) ([]byte, error) {
	buf := make([]byte, n)
	_, err := io.ReadFull(r, buf)
	if err != nil {
		return nil, err // io.EOF or io.ErrUnexpectedEOF, unwrapped on purpose
	}
	return buf, nil
}

Exit codes from main ​

go
// Command exitcode shows the run() error pattern: main is the only place that
// calls os.Exit, so every defer inside run has already executed when the
// process exits with a meaningful status code.
package main

import (
	"context"
	"errors"
	"flag"
	"fmt"
	"io"
	"os"
	"os/signal"
)

// Exit codes are part of the CLI contract; keep them in [0, 125].
const (
	exitOK       = 0
	exitFailure  = 1
	exitUsage    = 2
	exitConfig   = 3
	exitCanceled = 130 // 128 + SIGINT, the shell convention
)

var errConfig = errors.New("invalid configuration")

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	code := run(ctx, os.Args[1:], os.Stdout, os.Stderr)
	stop()
	os.Exit(code) // nothing deferred in main: os.Exit would skip it
}

func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
	fs := flag.NewFlagSet("exitcode", flag.ContinueOnError)
	fs.SetOutput(stderr)
	workers := fs.Int("workers", 1, "number of workers (1-64)")
	if err := fs.Parse(args); err != nil {
		if errors.Is(err, flag.ErrHelp) {
			return exitOK
		}
		return exitUsage
	}

	cleanup := func() { fmt.Fprintln(stdout, "cleanup ran") }
	defer cleanup() // runs before main reaches os.Exit

	if err := work(ctx, *workers); err != nil {
		fmt.Fprintln(stderr, "error:", err) // the one place the error is printed
		switch {
		case errors.Is(err, errConfig):
			return exitConfig
		case errors.Is(err, context.Canceled):
			return exitCanceled
		default:
			return exitFailure
		}
	}
	fmt.Fprintln(stdout, "done")
	return exitOK
}

func work(ctx context.Context, workers int) error {
	if workers < 1 || workers > 64 {
		return fmt.Errorf("workers=%d: %w", workers, errConfig)
	}
	return ctx.Err()
}

Retry decisions ​

Error (after errors.Is/As)MeaningRetry?
context.DeadlineExceeded from a downstream callBudget used upYes, with backoff and a fresh budget, if idempotent
net.Error with Timeout()Network timeoutYes, if idempotent
context.CanceledOur caller gave upNo: stop immediately
*pgconn.PgError Code 40001 / 40P01Serialization failure / deadlockYes, the whole transaction
ErrNotFound, *ValidationErrorDeterministicNo
errors.ErrUnsupportedNot possible hereNo: fall back
io.ErrUnexpectedEOF on a streamTruncated transferYes, re-fetch the whole object
Recovered *PanicErrorBugNo: alert

Rules: classify once, retry only idempotent operations, cap attempts, respect the caller's context. Backoff, jitter and budgets are in Timeouts, Retries & Jitter.

Choosing ​

error, panic or exit?Something went wrong in f()Expected at runtime? (input,network, disk, missing row)Bug or impossible state?(broken invariant, Must* helper)Program cannot start?(bad flags, config, port)return errorwrap with %w + contextsentinel / type / opaquethe default, ~alwayspanicnever across a package APIrecover only at a boundary(request, goroutine, parser)run() error, then os.Exitonly in main; defers done firstlog.Fatal = print + os.Exit(1)panic exits with status 2
SituationRecommendationExtra techniqueReason
Library function, failure the caller may handleReturn errorSentinel or type only if callers branch on itCallers decide, API stays small
Caller must branch on one conditionExported sentinel + %werrors.IsCheap, readable
Caller needs dataExported error type, pointer receivererrors.As / AsTypeStructured response
Caller needs a property (retryable)Behaviour interfaceTimeout(), Temporary()No import coupling
Error from a dependency you might replaceTranslate or %vwrapcheck exceptions for own packagesDo not leak implementation
Validation with many fieldserrors.Join or own Unwrap() []error422 with a listUser fixes everything at once
Impossible state / programmer bugpanicTests that hit the branchFail fast and loud
Constant input at start-upMust* helperregexp.MustCompile, template.MustPanics only on a code bug
Program cannot startrun() returns error/code, main exitsExit code table in --helpDefers run, scriptable
Long-running goroutineRecover at its topChannel or errgroup for the errorOne bad job ≠ outage
HTTP/gRPC edgeOne adapter + recover middleware/interceptorProblem Details / status.ErrorOne log line, no leaks
Cleanup of a written resourceDeferred errors.Join into named resultTest with a failing CloseNo silent data loss

For PHP/Laravel developers ​

PHP 7+ has a single hierarchy: everything throwable implements Throwable ("the base interface for any object that can be thrown via a throw statement, including Error and Exception"; user classes cannot implement it directly). Exception covers expected failures, Error (TypeError, DivisionByZeroError) covers engine-level problems — the closest analogue to Go's runtime.Error. Laravel's exception handler, configured with withExceptions in bootstrap/app.php, is the boundary that decides how exceptions "are reported and rendered"; dontReportDuplicates() ensures "a single instance of an exception is only ever reported once" — the same handle once idea.

PHP / LaravelGoNote
throw new OrderNotFound($id)return fmt.Errorf("load order %s: %w", id, ErrNotFound)Visible in the signature
catch (OrderNotFound $e)errors.Is(err, ErrNotFound)Identity, not class
catch (ValidationException $e) { $e->errors() }errors.As(err, &ve) then ve.FieldType with fields
$previous constructor argument, getPrevious()%w, errors.UnwrapChain of causes
finally { fclose($h); }defer f.Close()Defer runs on panics too
Error / TypeError (engine)runtime.Error panicBugs, not flow control
set_exception_handler, Laravel Handler::renderBoundary adapter / recover middlewareOne place decides and logs
report() then throw againlog and returnAnti-pattern in both
exit(1)os.Exit(1)PHP still runs shutdown functions and destructors but never finally; Go runs nothing
Stack trace on every exceptionNo trace; wrap messages; debug.Stack() for panicsCheaper errors
php
<?php
// PHP: the failure path is invisible in the signature; cleanup lives in finally.
function loadOrder(string $id): Order
{
    $h = fopen("/data/orders/$id.json", 'r');
    try {
        return Order::fromJson(stream_get_contents($h));
    } catch (JsonException $e) {
        throw new InvalidOrder("order $id: invalid json", previous: $e);
    } finally {
        fclose($h);
    }
}

The Go version returns (Order, error), wraps with %w where PHP passes previous:, and uses defer f.Close() right after a successful os.Open where PHP uses finally.

In architecture: from a single process to a distributed system ​

Wrap on the way up, handle once at the boundaryRepositorysql.ErrNoRowstranslate: return ErrNotFoundServicefmt.Errorf("load order %s: %w")no log, no status codeBoundary adaptererrors.Is / errors.As oncelog once + recover panicsHTTP: 404 application/problem+jsongRPC: status.Error(codes.NotFound)CLI: stderr + os.Exit(code)Anti-patterns this replaceslog-and-return in every layer (one failure, three log lines)err.Error() in the response body; strings.Contains on messagesMessage read by a human: "load order o-9: order not found" — lowercase, no trailing punctuation, colon-separated context.

Monolith: one process, one database ​

All errors are in-process values. The simplest correct shape is the one in After: repositories translate driver errors into package sentinels, services wrap with %w and IDs, and one HTTP adapter maps errors to statuses and logs once. One recover middleware sits at the router; every go statement in background jobs gets its own recover. When a failure must be durable — a job that failed after all retries — store a classification, never the raw error text that may contain secrets:

sql
-- Persist failure classification for later inspection or replay.
CREATE TABLE job_failures (
    id          bigserial PRIMARY KEY,
    job_id      text        NOT NULL,
    kind        text        NOT NULL CHECK (kind IN ('timeout','canceled','unsupported','permanent','panic')),
    code        text,                       -- e.g. SQLSTATE 40001, gRPC code, HTTP status
    message     text        NOT NULL,       -- the wrapped chain, scrubbed of secrets
    stack       text,                       -- debug.Stack() only for kind = 'panic'
    failed_at   timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX job_failures_kind_time ON job_failures (kind, failed_at DESC);

Modular monolith and multiple databases ​

Module boundaries are API boundaries, so the three styles become a contract question. The billing module exports billing.ErrCardDeclined and *billing.DeclineError; the orders module imports only those, never pgconn.PgError from billing's database. Each module translates its own storage errors at its edge; wrapcheck configured with your module's path as "own package" enforces that third-party errors are wrapped where they enter. Opaque errors between modules give each team freedom to swap storage.

Microservices ​

Errors do not cross the network; codes and documents do. The order service calls inventory over gRPC: inventory returns status.Error(codes.FailedPrecondition, "out of stock") plus a richer-error-model detail (a protobuf message such as google.rpc.ErrorInfo with reason OUT_OF_STOCK); the order service's client adapter does status.Code(err) and translates back into its own orders.ErrOutOfStock, which its HTTP adapter maps to 409 with application/problem+json. Deadlines propagate as gRPC deadlines; on the server ctx.Err() becomes context.DeadlineExceeded, which maps back to codes.DeadlineExceeded — classify it as retryable only if the operation is idempotent (see API Idempotency). A recovery interceptor in each service converts handler panics to codes.Internal with no internals in the message. Flow: POST /orders → orders Reserve() gRPC → inventory FailedPrecondition → orders ErrOutOfStock → client 409 {"type":"/problems/out-of-stock"}.

Distributed data: replicas, caches, queues and multi-region ​

At this stage the meaning of an error is often "unknown outcome". A context.DeadlineExceeded on a write to a remote primary does not tell you whether the commit happened; the error type must say so (ErrOutcomeUnknown) so the caller reconciles instead of blindly retrying. Message consumers translate errors into broker actions — ack, retry with delay, or dead-letter (see Dead-Letter Queue); a panic in a consumer must become a "retry or park" decision, not a crashed pod that redelivers the same poison message forever. Cache layers turn backend errors into fallbacks (serve stale) and must not cache the error itself unless deliberately (negative caching of ErrNotFound with a short TTL).

Scaling path: 1×, 10×, 100× ​

At 1× the rules on this page suffice: %w, one boundary, recover at goroutine tops. At 10× error rates become metrics: the boundary increments errors_total{kind,code} from the classifier, context.Canceled is excluded from SLO burn, and logs are sampled for repeated identical errors. At 100× the cost of an error path matters: no stack capture on expected errors, no string formatting of huge payloads into messages, errors.Is on short trees, and panics treated as incidents with crash-loop alerts — a single panicking message replayed across 500 consumers is an outage, so the recover boundary parks it after N attempts.

Lab ​

All commands run from docs/snippets/go/errors-panic-recover-defer. Steps 1–5 were run on the host (Go 1.27.4, macOS arm64) and the output below is real; step 6 needs golangci-lint and is expected, not run.

1. Tests and the race detector.

bash
go vet ./... && go test -race ./...
text
ok  	academy/errors-panic-recover-defer/after
ok  	academy/errors-panic-recover-defer/before
ok  	academy/errors-panic-recover-defer/classify
ok  	academy/errors-panic-recover-defer/deferorder
ok  	academy/errors-panic-recover-defer/exitcode
ok  	academy/errors-panic-recover-defer/httpboundary
?   	academy/errors-panic-recover-defer/labpanic	[no test files]
ok  	academy/errors-panic-recover-defer/opaque
ok  	academy/errors-panic-recover-defer/recoverboundary
ok  	academy/errors-panic-recover-defer/wrapping

2. Every runtime message. The program:

go
// Command labpanic reproduces the exact runtime messages discussed in the
// chapter. Run: go run ./labpanic -case=index (see the Lab section).
package main

import (
	"errors"
	"flag"
	"fmt"
	"log"
	"os"
	"runtime/debug"
	"time"
)

type user struct{ Name string }

func main() {
	c := flag.String("case", "index", "index|nilmap|nilptr|assert|custom|repanic|goroutine|exit|fatal|stack|deadlock")
	flag.Parse()
	defer fmt.Println("deferred in main ran")

	switch *c {
	case "index":
		s := []int{1, 2, 3}
		i := len(s)
		fmt.Println(s[i])
	case "nilmap":
		var m map[string]int
		m["a"] = 1
	case "nilptr":
		var u *user
		fmt.Println(u.Name)
	case "assert":
		var v any = "text"
		fmt.Println(v.(int))
	case "custom":
		panic(errors.New("config: missing DATABASE_URL"))
	case "repanic":
		defer func() {
			v := recover()
			fmt.Println("recovered:", v, "- re-panicking")
			panic(v)
		}()
		panic("PANIC")
	case "goroutine":
		defer func() { fmt.Println("main's recover sees:", recover()) }()
		go func() { panic("worker died") }()
		time.Sleep(100 * time.Millisecond)
	case "exit":
		os.Exit(3)
	case "fatal":
		log.Fatal("cannot start: port in use")
	case "stack":
		fmt.Printf("%s", debug.Stack())
	case "deadlock":
		ch := make(chan int)
		<-ch
	}
}
bash
go build -trimpath -o /tmp/labpanic ./labpanic
for c in index nilmap nilptr assert custom repanic goroutine exit fatal deadlock; do
  /tmp/labpanic -case=$c; echo "exit=$?"; done

Trimmed output (the --- separators are added here for reading):

text
deferred in main ran
panic: runtime error: index out of range [3] with length 3

goroutine 1 [running]:
main.main()
	academy/errors-panic-recover-defer/labpanic/main.go:26 +0x47c
exit=2
--- repanic
recovered: PANIC - re-panicking
deferred in main ran
panic: PANIC [recovered, repanicked]

goroutine 1 [running]:
main.main.func1()
	academy/errors-panic-recover-defer/labpanic/main.go:42 +0x74
panic({0x102bba398?, 0x102ba4040?})
	runtime/panic.go:859 +0x120
main.main()
	academy/errors-panic-recover-defer/labpanic/main.go:44 +0x430
exit=2
--- goroutine (main's recover never runs, its defer never prints)
panic: worker died

goroutine 18 [running]:
main.main.func3()
	academy/errors-panic-recover-defer/labpanic/main.go:47 +0x2c
created by main.main in goroutine 1
	academy/errors-panic-recover-defer/labpanic/main.go:47 +0x3c4
exit=2
--- exit: no output, "deferred in main ran" missing
exit=3
--- fatal: "deferred in main ran" missing
2026/11/26 10:22:31 cannot start: port in use
exit=1
--- deadlock
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
exit=2

Observe: in index, nilmap, nilptr, assert, custom and repanic the line deferred in main ran is printed before the panic text — defers ran while unwinding. In goroutine, exit, fatal and deadlock it is missing.

3. Exit codes and defers with run().

bash
go build -trimpath -o /tmp/exitcode ./exitcode
/tmp/exitcode; echo "exit=$?"
/tmp/exitcode -workers=0; echo "exit=$?"
/tmp/exitcode -nope; echo "exit=$?"
text
done
cleanup ran
exit=0
error: workers=0: invalid configuration
cleanup ran
exit=3
flag provided but not defined: -nope
Usage of exitcode:
  -workers int
    	number of workers (1-64) (default 1)
exit=2

4. Defer and recover rules as tests.

bash
go test -count=1 -v ./deferorder ./recoverboundary
text
--- PASS: TestOrderIsLIFO (0.00s)
--- PASS: TestArgumentsEvaluatedAtDefer (0.00s)
--- PASS: TestNamedResult (0.00s)
--- PASS: TestDeferInLoop (0.00s)
--- PASS: TestCopyKeepsBothErrors (0.00s)
--- PASS: TestDoReturnsErrorsUnchanged (0.00s)
--- PASS: TestDoConvertsRuntimePanic (0.00s)
--- PASS: TestPanicNil (0.00s)
--- PASS: TestDoStrictRepanicsRuntimeErrors (0.00s)
--- PASS: TestGoroutineBoundary (0.00s)
--- PASS: TestRecoverMustBeCalledDirectly (0.00s)

Then break one on purpose: in recover.go change Do's deferred function to call a helper that calls recover(); TestDoConvertsRuntimePanic now crashes the test binary with panic: runtime error: index out of range [3] with length 0.

5. What defer costs.

bash
go test -run '^$' -bench . -count 3 ./deferorder
text
cpu: Apple M4 Pro
BenchmarkUnlockDirect-12         	511367720	         2.194 ns/op
BenchmarkUnlockDefer-12          	320549635	         3.720 ns/op
BenchmarkUnlockDeferInLoop-12    	64159831	        18.13 ns/op

6. Linters (expected, not run). With golangci-lint v2 installed, errorlint on a file that compares, type-asserts and formats errors with %v:

bash
golangci-lint run --enable-only errcheck,errorlint,wrapcheck ./...
text
x.go:12:5: comparing with == will fail on wrapped errors. Use errors.Is to check for a specific error (errorlint)
x.go:15:9: type assertion on error will fail on wrapped errors. Use errors.As to check for specific errors (errorlint)
x.go:20:10: non-wrapping format verb for fmt.Errorf. Use `%w` to format errors (errorlint)

The messages are copied from the errorlint source; file and line numbers are illustrative. Note what no linter reports: before/orders.go uses strings.Contains(err.Error(), ...) and log and return, and passes all three. Only review catches those.

Common misconceptions ​

BeliefReality
panic/recover is Go's try/catchPanics are for bugs; packages must not expose them; error is the normal path
A recover in main protects every goroutineRecover works only on its own goroutine; any other goroutine's panic kills the process
recover() works anywhere in a deferred call chainOnly when called directly by the deferred function
%w is always better than %vWrapping makes the cause API; hide implementation details
errors.Unwrap walks the whole treeIt follows only Unwrap() error; it returns nil for joined errors
errors.Join(nil, nil) is a non-nil empty errorIt returns nil
defer runs at the end of the loop iterationAt the end of the function
defer fmt.Println(x) prints the final xArguments are evaluated at the defer statement
defer is too slow for hot pathsOpen-coded defers cost about 1.5 ns here; only defers in loops are slow
log.Fatal shuts down gracefullyIt calls os.Exit(1); defers do not run
An unrecovered panic exits with 1It exits with 2
Returning a nil *MyErr as error is nilThe interface is non-nil (typed nil)
Log errors where they happen for better debuggingHandle once: wrap below, log at the boundary
io.EOF should be wrapped like other errorsRead must return it unwrapped; it is a signal
context canceled is a server errorThe client left; it is not an incident
Stack traces belong on every errorMessages are the trace; capture stacks for panics
Go's net/http turns a panic into a 500It logs and drops the connection; the client sees a reset

Cheat sheet ​

TopicRemember
Signaturefunc F(...) (T, error), error last, return nil literally on success
Messageslowercase, no trailing punctuation, "op key: %w"
Wrap%w = cause is API; %v = text only
Inspecterrors.Is for values, errors.As (AsType 1.26+) for types/behaviour, never == on wrapped errors
Many errorserrors.Join, multiple %w (1.20+), Unwrap() []error
Stylessentinel (which), type (details), opaque (only that), behaviour interface (a property)
Handle oncewrap below, decide + log once at the boundary; no log and return
Signalsio.EOF unwrapped; context.Canceled quiet; DeadlineExceeded maybe retry; ErrUnsupported fall back
deferLIFO, args now, closures later, function scope, named results editable
Close errorsnamed result + deferred errors.Join(err, f.Close()) for writers
panicbugs, impossible states, Must*, failed init; exit status 2
recoveronly directly in a deferred function, only own goroutine; capture debug.Stack() there
Boundariesnet/http recovers per request; your goroutines do not; ErrAbortHandler re-panic
Exitos.Exit and log.Fatal skip defers; main → os.Exit(run()); codes 0–125
WireHTTP: RFC 9457 application/problem+json; gRPC: status.Error/status.Code
Lintgo vet, errcheck, errorlint, wrapcheck

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A repository returns fmt.Errorf("get user: %v", sql.ErrNoRows) and the handler checks errors.Is(err, sql.ErrNoRows). What happens, and what are the two correct fixes? Must-know ​

Answer

Answer: errors.Is is false because %v flattened the cause to text, so the handler returns 500 for a missing user. Fix 1: translate in the repository to your own sentinel (return ErrUserNotFound) and have the handler check that. Fix 2: wrap with %w, accepting that sql.ErrNoRows is now part of the repository's API. Fix 1 is usually better. See Wrapping.

2 — What does this print? for i := 0; i < 3; i++ { defer fmt.Print(i) } Must-know ​

Answer

Answer: 210: deferred calls run LIFO and each i was evaluated when its defer executed. See defer.

3 — A worker pool's job panics with a nil map write. main has defer func() { recover() }(). Does the process survive? Important ​

Answer

Answer: No. The panic is on the worker's goroutine; main's recover runs on goroutine 1 and never sees it. The process exits with status 2. The worker must defer its own recover. See Boundaries and lab step 2.

4 — Why does defer func() { logAndRecover() }() fail to recover, while defer logAndRecover() works? Important ​

Answer

Answer: recover returns nil unless "called directly by a deferred function". In the first form the deferred function is the anonymous closure, and recover is one call deeper. In the second the deferred function is logAndRecover itself. See recover.

5 — errors.Unwrap(errors.Join(a, b)) returns what, and how do you check for b? Good to know ​

Answer

Answer: nil: Unwrap only follows Unwrap() error, and joined errors implement Unwrap() []error. Use errors.Is(err, b), which walks every branch. See Join.

6 — A CLI uses log.Fatal(err) after opening a temp directory with defer os.RemoveAll(dir). What goes wrong? Must-know ​

Answer

Answer: log.Fatal calls os.Exit(1), which runs no defers, so the temp directory is left behind. Return the error to main, let run() return, then exit. See Exiting.

7 — Your API's error rate jumped after you added logging at the handler boundary; most entries are context canceled. What is going on, and what do you change? Important ​

Answer

Answer: Clients navigating away or timing out on their side cancel the request context; queries then return context.Canceled. It is not a server failure. Classify it at the boundary, log at debug level, write no response and exclude it from error SLOs. See Signals.

8 — A function func Validate() error { var e *ValidationErrors; ...; return e } makes every request fail even when valid. Why? Important ​

Answer

Answer: It returns a typed nil: the error interface holds the type *ValidationErrors with a nil value, which is non-nil. Return a literal nil on success. See Custom error types.

9 — When is panicking acceptable in library code? Important ​

Answer

Answer: For programmer errors and impossible states (a broken invariant, an unreachable default), in Must* helpers whose input is constant, and in initialisation that cannot proceed. Never for input-dependent failures, and never let a panic cross the package API: recover it into an error. See panic.

10 — Why is defer f.Close() fine for a file you read but not for a file you wrote? Important ​

Answer

Answer: For a written file, Close may flush buffered data and report ENOSPC or an I/O error; it is your only signal that the data did not reach disk. Capture it with a named result and errors.Join(err, f.Close()). For a read-only file the Close error carries no data-loss information. See the defer snippet.

11 — Which status should an HTTP API return for context.DeadlineExceeded from a downstream call, and what must never be in the body? Important ​

Answer

Answer: 504 (the gateway timed out waiting for a dependency) with an application/problem+json body; never err.Error() of internal errors, which may contain hostnames, SQL or paths. See Error values across APIs.

Glossary ​

TermMeaning
error interfacePredeclared interface { Error() string }; nil means no error
errors.NewCreates a distinct error value with fixed text
fmt.ErrorfFormats a message into an error; with %w it wraps
%wfmt.Errorf verb that wraps an error operand (several allowed since 1.20)
%vFormats the operand's text; does not wrap
WrappingAdding context while keeping the cause reachable through Unwrap
Unwrap() error / Unwrap() []errorMethods that make an error wrap one or several others
Error treeThe structure formed by successive unwrapping; walked pre-order, depth-first
errors.IsReports whether any error in the tree matches a target value
errors.AsFinds the first error in the tree assignable to a target type and sets it
errors.AsTypeGeneric As returning (E, bool), Go 1.26
errors.UnwrapReturns the single wrapped error or nil
errors.JoinWraps several errors; nils dropped; newline-separated text
errors.ErrUnsupportedStandard sentinel for unsupported operations, Go 1.21
Sentinel errorExported package-level error value matched with errors.Is
Error typeExported type implementing error, matched with errors.As
Opaque errorAn error whose only promise is that it is non-nil
Behaviour interfaceSmall interface (Timeout() bool) tested with errors.As
Custom errorYour own type with Error(), optional Unwrap, Is, As
Typed nilA nil pointer stored in an interface, making the interface non-nil
Handle onceOne place inspects and acts on an error; others only wrap and return
Log and returnAnti-pattern: logging an error and also returning it
io.EOFSentinel for a graceful end of input; returned unwrapped
io.ErrUnexpectedEOFInput ended in the middle of a record
context.Canceledctx.Err() after cancel; text context canceled
context.DeadlineExceededctx.Err() after the deadline; text context deadline exceeded
deferSchedules a call for when the surrounding function returns
LIFOLast in, first out: the order deferred calls run
Argument evaluationDeferred call arguments are evaluated at the defer statement
Named resultA declared return variable that deferred closures can modify
Open-coded deferGo 1.14 compiler optimisation that inlines deferred calls
panicBuiltin that stops normal execution and unwinds the goroutine
PanickingThe termination sequence running defers up the goroutine
runtime.ErrorInterface of run-time panic values (index, nil map, nil dereference)
*runtime.PanicNilErrorValue of panic(nil) since Go 1.21
recoverBuiltin that stops panicking when called directly by a deferred function
Re-panicCalling panic again from a deferred function for values you do not handle
http.ErrAbortHandlerSentinel panic value that aborts a handler without a logged stack
Panic boundaryA goroutine top or request/message handler where panics become errors
os.ExitEnds the process immediately with a status; defers skipped
log.FatalPrint then os.Exit(1)
Exit codeProcess status: 0 success, 1 failure, 2 usage/panic, 128+N signal
Stack traceList of active frames; printed on crash, captured with debug.Stack
debug.StackReturns the calling goroutine's formatted stack
GOTRACEBACKEnvironment variable controlling crash traceback detail
pkg/errorsPre-1.13 library with Wrap/Cause and stacks; maintenance mode
Problem DetailsRFC 9457 JSON error body, application/problem+json
gRPC statuscodes.Code + message (+ details) carried by gRPC errors
errcheckLinter for unchecked error results
errorlintLinter for ==/type assertions on errors and %v vs %w
wrapcheckLinter for unwrapped errors from external packages
ThrowablePHP base interface for Exception and Error
finallyPHP/Java cleanup block; Go uses defer
exceptionNon-local error propagation in other languages; Go has none

References ​

Built by Morteza Negahi