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 for | Go to |
|---|---|
| Tables you can memorise in one minute | Everything in one minute |
| Why Go has no exceptions | Why it exists |
| Go 1.0 to 1.27: what changed and when | Where it comes from |
type error interface, errors.New, message style | The error interface |
fmt.Errorf("...: %w", err), %w vs %v | Wrapping |
errors.Is, errors.As, errors.Unwrap, errors.AsType | Inspecting the chain |
errors.Join, several %w in one call | Multiple errors |
| Sentinel vs error type vs opaque error (Cheney) | Three styles |
Custom error types with fields, custom Is, typed nil | Custom error types |
| Handle once, don't log and return, wrap without leaking | Handle once |
io.EOF, context.Canceled, context.DeadlineExceeded, errors.ErrUnsupported | Signals that are not failures |
defer: LIFO, argument evaluation, loops, cost | defer |
panic, runtime.Error, panic(nil) | panic |
recover, re-panic | recover and re-panic |
Goroutines and net/http as panic boundaries | Boundaries |
os.Exit, log.Fatal, exit codes | Exiting |
debug.Stack, pkg/errors | Stack traces |
errcheck, errorlint, wrapcheck, go vet | Linters |
| Bad code and the fix, side by side | Go |
| Exact runtime and vet messages | Mechanics |
| Tested solutions to each classic problem | Solving the classic problems |
| Which mechanism for which situation | Choosing |
Exceptions, Throwable, finally vs Go | For PHP/Laravel developers |
| Errors across processes, RPC and services | In architecture |
| Run every message yourself | Lab |
| Wrong beliefs, cheat sheet, self-check, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The toolbox. Every row is unpacked in the concept catalogue.
| Tool | In plain words | Tiny example | Since |
|---|---|---|---|
error | Any value with an Error() string method; nil means success | func Open(name string) (*File, error) | Go 1.0 |
errors.New | A new, unique error value with a fixed text | var ErrNotFound = errors.New("order not found") | Go 1.0 |
fmt.Errorf + %w | Add context and keep the cause inspectable | fmt.Errorf("load order %s: %w", id, err) | Go 1.13 |
fmt.Errorf + %v | Add 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.AsType | Generic As, returns the value and a bool | pe, ok := errors.AsType[*fs.PathError](err) | Go 1.26 |
errors.Unwrap | One step down a single-cause chain | errors.Unwrap(err) | Go 1.13 |
errors.Join / many %w | One error wrapping several | errors.Join(errA, errB) | Go 1.20 |
errors.ErrUnsupported | Standard "this operation is not supported" | errors.Is(err, errors.ErrUnsupported) | Go 1.21 |
defer | Run this call when the function returns, whatever path | defer f.Close() | Go 1.0 |
panic | Stop this goroutine's normal flow and unwind | panic("unreachable") | Go 1.0 |
recover | Inside a deferred call: stop the unwinding, get the value | if v := recover(); v != nil { ... } | Go 1.0 |
Error, panic or exit.
| Mechanism | Who sees it | Do defers run? | Exit status if unhandled | Use it for |
|---|---|---|---|---|
return err | The direct caller | Yes, normally | — (the caller decides) | Every expected failure: input, I/O, network, missing rows |
panic(v) | Deferred calls up the same goroutine | Yes, while unwinding | 2, with panic: ... and stacks | Bugs, broken invariants, Must* helpers, failed init |
| runtime panic | Same as panic, value is a runtime.Error | Yes | 2 | Index out of range, nil map write, nil dereference, failed type assertion |
os.Exit(code) | The parent process | No | code | Only in main, after run() has returned |
log.Fatal(...) | The parent process | No | 1 | Small tools; never in libraries or after resources are open |
fatal error: (runtime) | Nobody can recover it | No | 2 | Deadlock, concurrent map writes, out of memory |
The five defer rules.
| Rule | Example | Result |
|---|---|---|
| Deferred calls run in LIFO order | for i := 0; i < 3; i++ { defer fmt.Print(i) } | prints 210 |
Arguments are evaluated at the defer statement | x := 1; defer fmt.Println(x); x = 2 | prints 1 |
| A closure reads variables when it runs | defer func() { fmt.Println(x) }(); x = 2 | prints 2 |
| Deferred closures can change named results | func f() (n int) { defer func() { n *= 7 }(); return 6 } | returns 42 |
| Defers belong to the function, not the block | for ... { 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 throw | Failure is in the signature: (T, error) |
| Handling is optional; uncaught means crash | Handling is required by convention and by linters (errcheck) |
| Stack trace attached automatically | No stack trace; context is added by wrapping with messages |
try/catch by class hierarchy | errors.Is by identity, errors.As by type, behaviour by interface |
finally for cleanup | defer for cleanup, on every path including panics |
| Throwing is cheap to write, expensive to reason about | Returning is verbose to write, cheap to reason about |
| One mechanism for bugs and for expected failures | error 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
- "
panic/recoveris 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." Useerrorfor everything a caller might reasonably handle. - "Wrapping with
%wis 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." Wrappingsql.ErrNoRowsfrom a repository promises callers that you will keep returning it. - "A
recoverinmainprotects my whole program."recoverworks 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."
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 periodReal 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.
| Situation | Return | Why |
|---|---|---|
| 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 success | Document it: (n, err) like Read/Write | Callers then use n before checking err |
| "Not found" in a lookup | A 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."
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 want | Verb | Effect |
|---|---|---|
| Caller may inspect the cause (it is part of your contract) | %w | errors.Is/As see through |
| Caller sees the text only (cause is an implementation detail) | %v | Opaque: logs keep the words, API keeps its freedom |
| Several causes inspectable | %w ... %w (Go 1.20) | Unwrap() []error |
| Your own meaning, original hidden | Return 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."
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() []errorReal 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.
| Question | Before 1.13 | Since 1.13 | Since 1.26 |
|---|---|---|---|
Is it io.ErrUnexpectedEOF? | err == io.ErrUnexpectedEOF | errors.Is(err, io.ErrUnexpectedEOF) | same |
Give me the *fs.PathError | pe, 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 down | pkgerrors.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."
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) == nilReal 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.
| Need | Use | Note |
|---|---|---|
| Many independent failures, default text | errors.Join | Newline-separated; good for logs, not for one-line messages |
| Two causes with your own sentence | fmt.Errorf("x: %w; %w", a, b) | Go 1.20+ |
| Domain type with fields per item | Your type with Unwrap() []error | Keeps structure for the response body |
| First error from N goroutines, cancel the rest | errgroup.Group | See 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."
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).
| Style | Stdlib example | Match with | Caller coupling | Carries data |
|---|---|---|---|---|
| Sentinel error | io.EOF, sql.ErrNoRows, fs.ErrNotExist, context.Canceled | errors.Is | Imports your package; value is API | No (text only) |
| Error type | *fs.PathError, *strconv.NumError, *net.OpError, *json.SyntaxError | errors.As | Imports your package; fields are API | Yes |
| Behaviour interface | net.Error (Timeout()) | errors.As into an interface | Only the method set | The answer to one question |
| Opaque error | most fmt.Errorf("...: %v") | nothing | None | Text 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".
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 interfaceReal 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".
| Method | Purpose | Example in this page's snippets |
|---|---|---|
Error() string | Human text | order o-2: invalid amount: must not be negative |
Unwrap() error | Expose one cause | *PanicError exposes a runtime.Error value |
Unwrap() []error | Expose several | ValidationErrors |
Is(error) bool | Custom equality | *HTTPStatusError matches the status class |
As(any) bool | Custom conversion | Rare; prefer plain types |
Temporary() bool / Timeout() bool | Behaviour for callers | retryable, 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."
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.
| Layer | Does | Does not |
|---|---|---|
| Leaf (driver, repository) | Translate foreign errors into your package's meaning | Log, choose HTTP codes |
| Middle (service, use case) | Wrap with the operation and key IDs | Log, retry blindly, repeat information the callee already wrote |
Boundary (handler, consumer, main) | Inspect once, decide, log once with request context, respond | Re-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).
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 copyReal 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.
| Error | Meaning | Usual response | Retry? |
|---|---|---|---|
io.EOF | Normal end of stream | Stop reading, success | No |
io.ErrUnexpectedEOF | Truncated input | Report as corrupt input | Only if the source may resend |
context.Canceled | Caller/client gave up | Stop work, no error response, debug-level log | No |
context.DeadlineExceeded | Time budget used up | 504 / codes.DeadlineExceeded, count it | Maybe, with a new budget |
errors.ErrUnsupported | Operation not possible here | Fallback path or 501 | No |
http.ErrServerClosed | ListenAndServe returned after Shutdown | Normal shutdown, exit 0 | No |
sql.ErrNoRows | QueryRow().Scan found nothing | Translate to your not-found | No |
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.
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).
| Pattern | Correct | Pitfall |
|---|---|---|
| Release a lock | mu.Lock(); defer mu.Unlock() | Deferring before Lock succeeds |
| Close a file you only read | defer f.Close() | Ignoring the error is acceptable for read-only files |
| Close a file you wrote | Named result + errors.Join(err, f.Close()) | defer f.Close() loses "disk full" |
| Transaction | tx, err := db.BeginTx(...); if err != nil {...}; defer tx.Rollback() | Deferring before the error check (nil tx) |
| Loop over files | Body in a helper or closure, defer inside it | defer directly in the loop |
| Timing | defer func() { log.Println(time.Since(t)) }() | defer log.Println(time.Since(t)) evaluates now |
| Modify the result | Named result in a deferred closure | Unnamed 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).
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 2Real 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 value | Comes from | runtime.Error? | Message |
|---|---|---|---|
| Index out of range | s[i], a[i] | Yes | runtime error: index out of range [3] with length 3 |
| Nil map write | m["k"] = v on nil map | Yes | assignment to entry in nil map |
| Nil pointer dereference | u.Name with u == nil | Yes | runtime error: invalid memory address or nil pointer dereference + [signal SIGSEGV ...] |
| Failed type assertion | v.(int) with a string | Yes (*runtime.TypeAssertionError) | interface conversion: interface {} is string, not int |
| Integer divide by zero | a / b, b == 0 | Yes | runtime error: integer divide by zero |
panic(nil) | Explicit | Yes (*runtime.PanicNilError, Go 1.21+) | runtime error: panic called with nil argument |
panic("text") / panic(err) | Explicit | No (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].
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 beforeReal 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 recover | Effect | Verdict |
|---|---|---|
| Top of each goroutine you start | One bad job does not kill the process | Do it, convert to error, keep the stack |
| Per HTTP request / per message | Request fails, server lives | net/http already does it for handlers; add one for a proper 500 body |
| Inside a package, around a recursive parser | Internal panics become an error return | Fine, if they never escape |
| Around every call "just in case" | Hides bugs, corrupt state continues | Don't |
After runtime.Error you cannot reason about | State may be half-updated | Prefer 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."
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 2Real 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.
| Boundary | Recovers by default? | What you add |
|---|---|---|
net/http handler | Yes: logs, closes connection / RST_STREAM | Recover middleware writing a Problem Details 500; re-panic http.ErrAbortHandler |
Goroutine you start with go | No | defer + recover at its top, deliver an error on a channel |
errgroup.Group.Go | No: 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 handler | No by default | A recovery interceptor (see gRPC & Protobuf in Go) |
testing test function | The test fails and the binary stops | Nothing; use t.Fatal for expected failures |
init() | No | Nothing: 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).
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, $? == 1Real 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 code | Convention | Produced by |
|---|---|---|
| 0 | Success | return from main, os.Exit(0), -h with flag.ContinueOnError handled |
| 1 | General failure | log.Fatal, os.Exit(1), most tools |
| 2 | Usage error (Go flag); also unrecovered panic and fatal error: | flag.ExitOnError, runtime crash |
| 3–125 | Program-specific (document them) | os.Exit(n) |
| 126 / 127 | Shell: not executable / not found | The shell, not your program |
| 128+N | Killed 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.
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 +0x19cReal 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.
| Approach | Stack? | Cost | Today |
|---|---|---|---|
Wrap messages (%w) | No, a readable chain | Allocation per wrap | Standard |
pkg/errors.Wrap | Yes, at creation | Stack walk per error | Maintenance mode; migrate |
debug.Stack() in recover | Yes, of the panicking goroutine | Only on panic | Standard for boundaries |
GOTRACEBACK=all | All goroutines on crash | Crash only | Useful 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).
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 stringReal 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.
| Tool | Catches | Misses |
|---|---|---|
go vet | Bad %w operand, errors.As non-pointer target, deferred time.Since, %w on **E (1.27) | Ignored errors |
errcheck | _ = f()-less ignored errors, unchecked Close | Semantics: whether you handled it well |
errorlint | ==, type assertions, type switches on errors; %v vs %w with -errorf | Whether wrapping leaks internals |
wrapcheck | Returning third-party errors without context | Whether context is useful |
| Review | Handle 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.
// 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.
// 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.
| Trigger | Exact text | Exit status |
|---|---|---|
s[i], i == len(s) == 3 | panic: runtime error: index out of range [3] with length 3 | 2 |
| Write to nil map | panic: assignment to entry in nil map | 2 |
| Nil pointer field read | panic: runtime error: invalid memory address or nil pointer dereference then [signal SIGSEGV: segmentation violation code=0x2 addr=0x0 pc=...] | 2 |
v.(int) on a string | panic: interface conversion: interface {} is string, not int | 2 |
panic(errors.New("config: missing DATABASE_URL")) | panic: config: missing DATABASE_URL | 2 |
Recover then panic(v) again (Go 1.25+) | panic: PANIC [recovered, repanicked] | 2 |
Panic in a goroutine, main has a recover | panic: worker died ... created by main.main in goroutine 1 | 2 |
| All goroutines blocked | fatal error: all goroutines are asleep - deadlock! | 2 |
os.Exit(3) | nothing printed; defers skipped | 3 |
log.Fatal("cannot start: port in use") | 2026/11/26 10:22:31 cannot start: port in use; defers skipped | 1 |
http.Handler panics | server 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 time | x: %!w(string=str) | — |
vet, %w with a string | fmt.Errorf format %w has arg "not an error" of wrong type string | vet fails |
vet, %w with **MyErr | fmt.Errorf format %w has arg &e of wrong type **vetdemo.MyErr | vet fails |
vet, errors.As(err, pe) with a value | second argument to errors.As must be a non-nil pointer to either a type that implements error, or to any interface type | vet fails |
vet, defer log.Println(time.Since(t)) | call to time.Since is not deferred | vet fails |
ctx.Err() after cancel / deadline | context 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
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 runThe 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:
| Benchmark | ns/op (3 runs) | What it shows |
|---|---|---|
BenchmarkUnlockDirect | 2.194, 2.164, 2.195 | Lock + increment + Unlock, no defer |
BenchmarkUnlockDefer | 3.720, 3.705, 3.700 | Same with defer mu.Unlock(): ~1.5 ns more |
BenchmarkUnlockDeferInLoop | 18.13, 18.10, 17.97 | defer 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 error | HTTP status + RFC 9457 type | gRPC codes.* | Exit code (CLI) |
|---|---|---|---|
ErrNotFound | 404, /problems/not-found | NotFound | 1 or program-specific |
*ValidationError | 422 (or 400), /problems/validation + field | InvalidArgument | 2 for flag/usage errors |
ErrConflict / version mismatch | 409 | Aborted or AlreadyExists | — |
| Precondition (state machine) | 409 / 412 | FailedPrecondition | — |
context.DeadlineExceeded | 504 (gateway) | DeadlineExceeded | 1 |
context.Canceled | no response (client gone); log 499-style | Canceled | 130 on SIGINT |
errors.ErrUnsupported | 501 | Unimplemented | — |
| Rate limited | 429 + Retry-After | ResourceExhausted | — |
| Anything else | 500, about:blank, no internals | Internal (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
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Caller cannot tell not-found from failure | Sentinel + %w | ErrNotFound, errors.Is | Simple, cheap | Sentinel is permanent API |
| Caller needs details (field, path, code) | Error type | *ValidationError, errors.As | Structured responses | Type and fields are API |
| Many failures at once | errors.Join / Unwrap() []error | Collect, join, inspect | Nothing lost | Multi-line text |
| Driver errors leak through the API | Translate at the boundary | %v or own sentinel | Freedom to change storage | Callers lose detail (by design) |
| Same failure logged N times | Handle once | Wrap below, log at boundary | One line, full context | Discipline; review |
Close error on written files lost | Named result + deferred errors.Join | See Copy | No silent data loss | Slightly longer code |
| Files/locks held until function end | No defer in loops | Closure per iteration | Bounded resources | One more function |
| Panic in a goroutine kills the service | Recover at goroutine top | recoverboundary.Go | Process survives | Must still fix the bug |
| Handler panic gives client a reset | Recover middleware | Problem Details 500 | Proper response, one log | Doesn't fix half-updated state |
context canceled floods error logs | Classify signals | classify.Of | Honest error rates | Needs one shared helper |
| CLI exits 0 after failure | run() int + one os.Exit | exitcode | Defers run, correct $? | — |
err == x misses wrapped errors | errors.Is/As + errorlint | Linter in CI | Mechanical fix | Some 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.
// 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.
// 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
// 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.
// 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)
}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.
// 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
// 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
// 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) | Meaning | Retry? |
|---|---|---|
context.DeadlineExceeded from a downstream call | Budget used up | Yes, with backoff and a fresh budget, if idempotent |
net.Error with Timeout() | Network timeout | Yes, if idempotent |
context.Canceled | Our caller gave up | No: stop immediately |
*pgconn.PgError Code 40001 / 40P01 | Serialization failure / deadlock | Yes, the whole transaction |
ErrNotFound, *ValidationError | Deterministic | No |
errors.ErrUnsupported | Not possible here | No: fall back |
io.ErrUnexpectedEOF on a stream | Truncated transfer | Yes, re-fetch the whole object |
Recovered *PanicError | Bug | No: 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
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Library function, failure the caller may handle | Return error | Sentinel or type only if callers branch on it | Callers decide, API stays small |
| Caller must branch on one condition | Exported sentinel + %w | errors.Is | Cheap, readable |
| Caller needs data | Exported error type, pointer receiver | errors.As / AsType | Structured response |
| Caller needs a property (retryable) | Behaviour interface | Timeout(), Temporary() | No import coupling |
| Error from a dependency you might replace | Translate or %v | wrapcheck exceptions for own packages | Do not leak implementation |
| Validation with many fields | errors.Join or own Unwrap() []error | 422 with a list | User fixes everything at once |
| Impossible state / programmer bug | panic | Tests that hit the branch | Fail fast and loud |
| Constant input at start-up | Must* helper | regexp.MustCompile, template.Must | Panics only on a code bug |
| Program cannot start | run() returns error/code, main exits | Exit code table in --help | Defers run, scriptable |
| Long-running goroutine | Recover at its top | Channel or errgroup for the error | One bad job ≠ outage |
| HTTP/gRPC edge | One adapter + recover middleware/interceptor | Problem Details / status.Error | One log line, no leaks |
| Cleanup of a written resource | Deferred errors.Join into named result | Test with a failing Close | No 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 / Laravel | Go | Note |
|---|---|---|
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.Field | Type with fields |
$previous constructor argument, getPrevious() | %w, errors.Unwrap | Chain of causes |
finally { fclose($h); } | defer f.Close() | Defer runs on panics too |
Error / TypeError (engine) | runtime.Error panic | Bugs, not flow control |
set_exception_handler, Laravel Handler::render | Boundary adapter / recover middleware | One place decides and logs |
report() then throw again | log and return | Anti-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 exception | No trace; wrap messages; debug.Stack() for panics | Cheaper errors |
<?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
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:
-- 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.
go vet ./... && go test -race ./...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/wrapping2. Every runtime message. The program:
// 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
}
}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=$?"; doneTrimmed output (the --- separators are added here for reading):
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=2Observe: 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().
go build -trimpath -o /tmp/exitcode ./exitcode
/tmp/exitcode; echo "exit=$?"
/tmp/exitcode -workers=0; echo "exit=$?"
/tmp/exitcode -nope; echo "exit=$?"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=24. Defer and recover rules as tests.
go test -count=1 -v ./deferorder ./recoverboundary--- 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.
go test -run '^$' -bench . -count 3 ./deferordercpu: Apple M4 Pro
BenchmarkUnlockDirect-12 511367720 2.194 ns/op
BenchmarkUnlockDefer-12 320549635 3.720 ns/op
BenchmarkUnlockDeferInLoop-12 64159831 18.13 ns/op6. Linters (expected, not run). With golangci-lint v2 installed, errorlint on a file that compares, type-asserts and formats errors with %v:
golangci-lint run --enable-only errcheck,errorlint,wrapcheck ./...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
| Belief | Reality |
|---|---|
panic/recover is Go's try/catch | Panics are for bugs; packages must not expose them; error is the normal path |
A recover in main protects every goroutine | Recover works only on its own goroutine; any other goroutine's panic kills the process |
recover() works anywhere in a deferred call chain | Only when called directly by the deferred function |
%w is always better than %v | Wrapping makes the cause API; hide implementation details |
errors.Unwrap walks the whole tree | It follows only Unwrap() error; it returns nil for joined errors |
errors.Join(nil, nil) is a non-nil empty error | It returns nil |
defer runs at the end of the loop iteration | At the end of the function |
defer fmt.Println(x) prints the final x | Arguments are evaluated at the defer statement |
defer is too slow for hot paths | Open-coded defers cost about 1.5 ns here; only defers in loops are slow |
log.Fatal shuts down gracefully | It calls os.Exit(1); defers do not run |
| An unrecovered panic exits with 1 | It exits with 2 |
Returning a nil *MyErr as error is nil | The interface is non-nil (typed nil) |
| Log errors where they happen for better debugging | Handle once: wrap below, log at the boundary |
io.EOF should be wrapped like other errors | Read must return it unwrapped; it is a signal |
context canceled is a server error | The client left; it is not an incident |
| Stack traces belong on every error | Messages are the trace; capture stacks for panics |
Go's net/http turns a panic into a 500 | It logs and drops the connection; the client sees a reset |
Cheat sheet
| Topic | Remember |
|---|---|
| Signature | func F(...) (T, error), error last, return nil literally on success |
| Messages | lowercase, no trailing punctuation, "op key: %w" |
| Wrap | %w = cause is API; %v = text only |
| Inspect | errors.Is for values, errors.As (AsType 1.26+) for types/behaviour, never == on wrapped errors |
| Many errors | errors.Join, multiple %w (1.20+), Unwrap() []error |
| Styles | sentinel (which), type (details), opaque (only that), behaviour interface (a property) |
| Handle once | wrap below, decide + log once at the boundary; no log and return |
| Signals | io.EOF unwrapped; context.Canceled quiet; DeadlineExceeded maybe retry; ErrUnsupported fall back |
| defer | LIFO, args now, closures later, function scope, named results editable |
| Close errors | named result + deferred errors.Join(err, f.Close()) for writers |
| panic | bugs, impossible states, Must*, failed init; exit status 2 |
| recover | only directly in a deferred function, only own goroutine; capture debug.Stack() there |
| Boundaries | net/http recovers per request; your goroutines do not; ErrAbortHandler re-panic |
| Exit | os.Exit and log.Fatal skip defers; main → os.Exit(run()); codes 0–125 |
| Wire | HTTP: RFC 9457 application/problem+json; gRPC: status.Error/status.Code |
| Lint | go vet, errcheck, errorlint, wrapcheck |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
error interface | Predeclared interface { Error() string }; nil means no error |
errors.New | Creates a distinct error value with fixed text |
fmt.Errorf | Formats a message into an error; with %w it wraps |
%w | fmt.Errorf verb that wraps an error operand (several allowed since 1.20) |
%v | Formats the operand's text; does not wrap |
| Wrapping | Adding context while keeping the cause reachable through Unwrap |
Unwrap() error / Unwrap() []error | Methods that make an error wrap one or several others |
| Error tree | The structure formed by successive unwrapping; walked pre-order, depth-first |
errors.Is | Reports whether any error in the tree matches a target value |
errors.As | Finds the first error in the tree assignable to a target type and sets it |
errors.AsType | Generic As returning (E, bool), Go 1.26 |
errors.Unwrap | Returns the single wrapped error or nil |
errors.Join | Wraps several errors; nils dropped; newline-separated text |
errors.ErrUnsupported | Standard sentinel for unsupported operations, Go 1.21 |
| Sentinel error | Exported package-level error value matched with errors.Is |
| Error type | Exported type implementing error, matched with errors.As |
| Opaque error | An error whose only promise is that it is non-nil |
| Behaviour interface | Small interface (Timeout() bool) tested with errors.As |
| Custom error | Your own type with Error(), optional Unwrap, Is, As |
| Typed nil | A nil pointer stored in an interface, making the interface non-nil |
| Handle once | One place inspects and acts on an error; others only wrap and return |
| Log and return | Anti-pattern: logging an error and also returning it |
io.EOF | Sentinel for a graceful end of input; returned unwrapped |
io.ErrUnexpectedEOF | Input ended in the middle of a record |
context.Canceled | ctx.Err() after cancel; text context canceled |
context.DeadlineExceeded | ctx.Err() after the deadline; text context deadline exceeded |
defer | Schedules a call for when the surrounding function returns |
| LIFO | Last in, first out: the order deferred calls run |
| Argument evaluation | Deferred call arguments are evaluated at the defer statement |
| Named result | A declared return variable that deferred closures can modify |
| Open-coded defer | Go 1.14 compiler optimisation that inlines deferred calls |
panic | Builtin that stops normal execution and unwinds the goroutine |
| Panicking | The termination sequence running defers up the goroutine |
runtime.Error | Interface of run-time panic values (index, nil map, nil dereference) |
*runtime.PanicNilError | Value of panic(nil) since Go 1.21 |
recover | Builtin that stops panicking when called directly by a deferred function |
| Re-panic | Calling panic again from a deferred function for values you do not handle |
http.ErrAbortHandler | Sentinel panic value that aborts a handler without a logged stack |
| Panic boundary | A goroutine top or request/message handler where panics become errors |
os.Exit | Ends the process immediately with a status; defers skipped |
log.Fatal | Print then os.Exit(1) |
| Exit code | Process status: 0 success, 1 failure, 2 usage/panic, 128+N signal |
| Stack trace | List of active frames; printed on crash, captured with debug.Stack |
debug.Stack | Returns the calling goroutine's formatted stack |
GOTRACEBACK | Environment variable controlling crash traceback detail |
pkg/errors | Pre-1.13 library with Wrap/Cause and stacks; maintenance mode |
| Problem Details | RFC 9457 JSON error body, application/problem+json |
| gRPC status | codes.Code + message (+ details) carried by gRPC errors |
errcheck | Linter for unchecked error results |
errorlint | Linter for ==/type assertions on errors and %v vs %w |
wrapcheck | Linter for unwrapped errors from external packages |
Throwable | PHP base interface for Exception and Error |
finally | PHP/Java cleanup block; Go uses defer |
| exception | Non-local error propagation in other languages; Go has none |
References
- Go specification (language version go1.27): Defer statements, Handling panics, Errors, Run-time panics
- Effective Go (Errors, Panic, Recover, Defer); Go FAQ (Why does Go not have exceptions?, Why is my nil error value not equal to nil?); Go Code Review Comments
- Go blog: Defer, Panic, and Recover (2010), Error handling and Go (2011), Errors are values (2015), Working with Errors in Go 1.13 (2019)
- Release notes: Go 1.13, Go 1.14, Go 1.20, Go 1.21, Go 1.22, Go 1.23, Go 1.24, Go 1.25, Go 1.26, Go 1.27
- Standard library source (package docs; pkg.go.dev returned 403 to the fetcher, so the same doc comments were read from source): errors/wrap.go, errors/join.go, errors/errors.go, fmt/errors.go, runtime/error.go, runtime/debug/stack.go, context/context.go, io/io.go, os/proc.go, os/error.go, log/log.go, net/http/server.go, runtime/extern.go (GOTRACEBACK), flag/flag.go, x/sync errgroup.go;
go doc errors(Go 1.27.4) forAsType - Dave Cheney, Don't just check errors, handle them gracefully (2016); github.com/pkg/errors
- gRPC: Error handling guide, grpc-go status/status.go
- IETF: RFC 9457 Problem Details for HTTP APIs
- Linters: errcheck, go-errorlint (lint.go messages), wrapcheck, golangci-lint linters
- PHP: Throwable, Exception, Error, exit; Laravel 13 Error Handling