Errors
Go returns errors as plain values, so the rules are about what you add, what you hide and who decides. Here are those rules, the outputs of real runs, and one path from a storage error to an HTTP status.
- 1An error is a value. Add what this layer knows, and return it. Handle each error once.
- 2Wrap with %w when callers may test the cause. Use %v when the cause is your private detail.
- 3Compare with errors.Is and read with errors.As or errors.AsType, never with == or a string match.
- 4Panic means a bug or a broken startup. Recover only at a boundary, and turn the panic into an error.
package main
import "fmt"
type QueryError struct{ Query string }
func (e *QueryError) Error() string { return "bad query: " + e.Query }
func run(q string) *QueryError1 {
if q == "" {
return &QueryError{q}
}
return nil
}
func check(q string) error {
return run(q)2
}
func main() {
err := check("select 1")
fmt.Println(err == nil)3
fmt.Printf("%T %v\n", err, err != nil)
}- 1The concrete return type starts the bug.
- 2The nil pointer becomes an interface value with a type word.
- 3False, on the path that succeeded. The caller treats success as failure.
| return type of run | recorded output | status |
|---|---|---|
| *QueryError | false, *main.QueryError true | Never nil |
| error | true, <nil> false | Approved |
- The compiler accepts both, because *QueryError implements error.
- The fix is one word in a signature. The body does not change.
- staticcheck reports this as SA4023 at the comparison.
A function returns the error interface, never a concrete error pointer. A nil pointer in an interface is not a nil interface.
- The error type has one method: Error() string.
- A wrapped error is a small value that holds the text and the cause. Is and As walk those links.
An interface is a type word and a data word. It equals nil only when both are nil.
| kind | test | use it when |
|---|---|---|
| Sentinel | errors.Is | The caller branches on a condition. It becomes part of your API. |
| Typed | errors.AsType | The caller needs data: a field name, a retry time. |
| Opaque | none | The caller can only log and return. This is the default. |
| Behaviour | AsType on an interface | Many types share one question, such as Timeout(). |
Each exported error is a promise that you must keep. Export the fewest that callers need.
A sentinel for a condition, a type when the caller needs data, and an opaque error for everything else.
- 1*fmt.wrapError: "handler: user 7: not found"
- 2err == target: no
- 3Unwrap returns one error: go down
- 4*fmt.wrapError: "user 7: not found"
- 5err == target: no
- 6Unwrap returns one error: go down
- 7*errors.errorString: "not found"
- 8err == target: match
- %v in the middle ends the path, so the text still says "not found" and the test fails.
- A joined error gives a tree. The walk tries each branch in order and stops at the first match.
- errors.As and errors.AsType walk in the same order, but they test the type.
errors.Is goes depth first. At each node it compares, then tries an Is method, then follows Unwrap.
| you want | write | not | status |
|---|---|---|---|
| Test for a sentinel | errors.Is(err, ErrNotFound) | err == ErrNotFound | Approved |
| Read a typed error | e, ok := errors.AsType[*FieldError](err) | err.(*FieldError) | Approved |
| The same, before Go 1.26 | var e *FieldError; errors.As(err, &e) | errors.As(err, e) | Old go.mod |
| Report several failures | errors.Join(a, b) | A string built by hand | Approved |
| Wrap two causes in one line | fmt.Errorf("%w: %w", a, b) | Two nested Errorf calls | Approved |
| Match by content | An Is method on your type | strings.Contains(err.Error(), ...) | Never match text |
| Step down one level | Avoid it. Is and As walk for you. | errors.Unwrap(err) | Single wraps only |
| Wrap an error with a value receiver | fmt.Errorf("x: %w", value) | fmt.Errorf("x: %w", &value) | go vet checks this |
I use Is for a value, AsType for a type, and Join when several things failed. I never compare error text.
| situation | do this | why | status |
|---|---|---|---|
| A caller may act on the cause | Wrap with %w | Is and As still find it. | Approved |
| The cause is a detail of your package | Use %v, or return your own sentinel | A wrap makes the cause part of your API. | Approved |
| A storage error crosses into the domain | Translate: no row becomes ErrNotFound | Callers do not import your driver. | Approved |
| You can recover here | Handle it and return nil | Handled means done. Do not also return it. | Approved |
| You log it and return it | Choose one | Each layer logs it, so one failure prints many times. | Not approved |
| You write "failed to" in the wrap | Write "load user 7: ..." | A chain reads better with no repeated words. | Not approved |
| You write _ = f() | Handle it, or log it with a reason | A dropped error is the hardest bug to find. | Never swallow |
| A loop over items fails on one | Join, or stop at the first | Say which you chose, and why. | Depends on the API |
Each layer adds what only it knows. At a boundary I translate, so a lower layer's error does not become my API.
// Sentinels are values. Callers test them with errors.Is,
// so each one is part of the package API.
var (
ErrNotFound = errors.New("not found")1
ErrConflict = errors.New("conflict")
ErrInvalid = errors.New("invalid")
)- 1A package variable. Each errors.New call makes a distinct value.
// FieldError carries data that a sentinel cannot.
type FieldError struct {
Field string
Reason string
}
func (e *FieldError) Error() string1 {
return e.Field + ": " + e.Reason
}
// Is lets errors.Is(err, ErrInvalid) match every
// FieldError, so callers need only one test.
func (e *FieldError) Is(target error) bool2 {
return target == ErrInvalid
}- 1A pointer receiver, so the pointer is the error. Wrap and test the pointer.
- 2errors.Is calls this at each step of the walk.
An Is method lets a typed error also match a sentinel, so callers need only one test.
// User is the input to Validate.
type User struct {
Email string
Age int
}
// Validate reports every bad field, not only the first.
// Join skips nil, and it returns nil if all are nil.
func Validate(u User) error {
var email, age error1
if !strings.Contains(u.Email, "@") {
email = &FieldError{"email", "must contain @"}
}
if u.Age < 0 {
age = &FieldError{"age", "must not be negative"}
}
return errors.Join(email, age)2
}- 1Interface variables, so a clean field stays a real nil. See panel A.
- 2Join drops nil values. With two nil values, it returns nil.
Validation reports all fields, so the user fixes them in one pass. Join returns nil when no field failed.
// Row is a stored record.
type Row struct{ Name string }
// DB is the storage layer. It returns ErrNoRow.
type DB interface {
Query(ctx context.Context, id int) (Row, error)
}
// ErrNoRow belongs to the storage layer.
var ErrNoRow = errors.New("no row")
// Load adds what only this layer knows: the id. It also
// translates the storage sentinel into a domain one.
func Load(ctx context.Context, db DB, id int) (Row, error) {
r, err := db.Query(ctx, id)
switch {
case errors.Is(err, ErrNoRow):1
return Row{}, fmt.Errorf("user %d: %w", id, ErrNotFound)2
case err != nil:
return Row{}, fmt.Errorf("user %d: %w", id, err)3
}
return r, nil
}- 1The boundary between storage and domain.
- 2The wrap adds the id. The domain sentinel replaces the storage one.
- 3Other errors keep their cause, so context errors stay testable.
The storage sentinel stops at this layer. Callers see ErrNotFound with the id, and they never import the driver.
// Publish hides the broker error behind %v. The text
// stays for the log, but no caller can test for it, so
// the broker stays an internal detail of this package.
func Publish(send func() error) error {
if err := send(); err != nil {
return fmt.Errorf("publish: %v: %w", err, ErrUnavailable1)
}
return nil
}
// ErrUnavailable is the one thing callers may test for.
var ErrUnavailable = errors.New("unavailable")- 1One verb of each: the broker text stays readable, and only ErrUnavailable is testable.
%v keeps the text for the log and breaks the chain, so no caller can depend on my broker.
// Save returns the Close error too. A write can succeed
// in a buffer and fail at Close, so Close must not be
// dropped. The named result lets the defer change it.
func Save(open func() (io.WriteCloser, error), data []byte) (err error)1 {
f, err := open()
if err != nil {
return fmt.Errorf("save: %w", err)
}
defer func() {
if cerr := f.Close(); cerr != nil {
err = errors.Join(err, fmt.Errorf("save: %w", cerr))2
}
}()
if _, err := f.Write(data); err != nil {
return fmt.Errorf("save: %w", err)
}
return nil
}- 1A named result, so the defer can change what the function returns.
- 2Keeps both failures. A plain assignment would replace the write error.
A deferred Close joins its error into the named result. For a write, Close can be the call that fails.
| situation | use | status |
|---|---|---|
| Bad input, a missing row, a network failure | Return an error | Approved |
| A regular expression or template in the source is wrong | Panic at startup | Approved |
| A state the code proves cannot happen | Panic: it is a bug | Approved |
| One request crashes in a server | Recover at the boundary | Boundary only |
| Panic and recover as control flow inside a package | Return an error | Inside one parser only |
| A panic crosses a package API | Return an error | Not approved |
| A panic in a goroutine you started | Recover in that goroutine | main cannot catch it |
// Must is for values known at startup, such as a regular
// expression in the source. A failure is a bug, and the
// program must not start.
func Must[T any](v T, err error) T {
if err != nil {
panic(err)1
}
return v
}
var slug = Must(2regexp.Compile(`^[a-z0-9-]+$`))- 1The input is in the source, so a failure is a bug. The program must not start.
- 2Runs at package initialization, so the first test finds a bad pattern.
I panic for a bug or an impossible state, and for broken startup config. Everything a user or a network can cause is an error.
// Protect stops a panic at a boundary and returns it as
// an error. One bad request must not end the process.
func Protect(fn func() error) (err error) {
defer func() {
if r := recover()1; r != nil {
err = fmt.Errorf("panic: %v\n%s", r, debug.Stack()2)
}
}()
return fn()
}- 1Works only when the deferred function calls it directly, in the panicking goroutine.
- 2Take the stack here. After this function returns, the panic frames are gone.
Since Go 1.25, a recovered and repeated panic prints: panic: boom [recovered, repanicked]
Recover runs in a deferred function at the boundary. It turns the panic into an error and keeps the stack for the log.
// ErrBackendSlow names why the deadline was set.
var ErrBackendSlow = errors.New("backend too slow")
// Fetch gives the caller the reason, not only "deadline
// exceeded": context.Cause returns ErrBackendSlow.
func Fetch(
ctx context.Context,
d time.Duration,
call func(context.Context) error,
) error {
ctx, cancel := context.WithTimeoutCause(ctx, d, ErrBackendSlow)1
defer cancel()
if err := call(ctx); err != nil {
if cause := context.Cause(ctx)2; cause != nil3 {
return fmt.Errorf("fetch: %w", cause)
}
return fmt.Errorf("fetch: %w", err)
}
return nil
}- 1Go 1.21. Cause returns this error when the timer fires.
- 2Go 1.20. It returns the parent cause if the parent ended first.
- 3Nil means the context is still live, so the call failed by itself.
ctx.Err only says canceled or deadline exceeded. I set a cause, so the error says which limit fired.
| the error | status | the client gets |
|---|---|---|
| user 7: not found | 404 | {"error":"user 7: not found"} |
| create: conflict | 409 | {"error":"create: conflict"} |
| signup: age: must not be negative | 400 | {"error":"invalid","field":"age"} |
| parse: invalid | 400 | {"error":"parse: invalid"} |
| fetch: backend too slow | 504 | {"error":"fetch: backend too slow"} |
| context canceled | 499 | {"error":"context canceled"} |
| dial db: connection refused | 500 | {"error":"internal error"} |
499 is not in the HTTP standard. The client has left, so no one reads it. In the logs, it separates a client that left from a server failure.
One function maps errors to status codes. An unknown error is a 500 with a fixed message, and the real text goes to the log.
// failure is the one place that turns an error into a
// status. An error it does not know is a 500.
func failure(err error) (int, map[string]any) {
if fe, ok := errors.AsType[*FieldError](err)1; ok {
return 400, map[string]any{
"error": "invalid", "field": fe.Field,
}
}
code := 500
switch {
case errors.Is(err, ErrInvalid):
code = 400
case errors.Is(err, ErrNotFound):
code = 404
case errors.Is(err, ErrConflict):
code = 409
case errors.Is(err, ErrBackendSlow):
code = 504
case errors.Is(err, context.Canceled):
code = 499
default:
log.Printf("internal: %v", err)2
err = errors.New("internal error")3
}
return code, map[string]any{"error": err.Error()}
}- 1Before the switch, because a FieldError also matches ErrInvalid.
- 2The one place where an unknown error is logged. The handler layers do not log it.
- 3An error text can hold a connection string. The client gets a fixed message.
The typed case comes first, because it matches ErrInvalid too. New domain errors add one case.
// route has one exit for errors and one for panics.
func route(status int, fn func(*http.Request) (any, error)) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
code := status1
var v any
err := Protect(func() error {2
var err error
v, err = fn(r)
return err
})
if err != nil {
code, v = failure(err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
if err := json.NewEncoder(w).Encode(v); err != nil {
log.Printf("encode: %v", err)3
}
})
}- 1A copy per request. status is shared by every request on this route.
- 2A panic becomes a 500 for this request, and the server keeps running.
- 3The status is sent, so this error can only be logged.
This extends the wrapper in the 45-minute build kit (K1) with typed errors and a boundary recover.
Each route returns a value and an error. One wrapper handles both, and it also stops a panic.
| since | what changed | what it means here |
|---|---|---|
| 1.13 | fmt.Errorf %w. errors.Unwrap, Is and As. | The base of this sheet. |
| 1.20 | errors.Join. Multiple %w. Unwrap() []error. context.WithCancelCause and context.Cause. | An error can be a tree, as panel D shows. |
| 1.21 | context.WithDeadlineCause and WithTimeoutCause. errors.ErrUnsupported. panic(nil) becomes *runtime.PanicNilError. | A non-nil recover result always means a panic. |
| 1.25 | A recovered and repeated panic prints [recovered, repanicked] and does not repeat the text. | Crash logs from panel M are shorter. |
| 1.26 | errors.AsType. fmt.Errorf("x") allocates about as little as errors.New("x"). signal.NotifyContext sets a cause. | Prefer AsType: it needs no target variable, and it was 9 times faster here. |
| 1.27 | go vet reports %w with a pointer to a type that implements error by value. net UnixConn reads return io.EOF directly. | vet prints: %w wants operand of error type Code, not pointer type *Code (defeats errors.Is). Is and AsType both returned false on that wrap. |
| when | the moment | what to do or say |
|---|---|---|
| build | You start the service. | Write ErrNotFound, ErrConflict and ErrInvalid first. The store and the handler share them. |
| build | A handler needs a status code. | Do not choose it in the handler. Add a case to failure, with a row in a table test. |
| build | A request has bad JSON. | Wrap with fmt.Errorf("%w: %v", ErrInvalid, err). The client gets a 400 and the reason. |
| talk | "Why not exceptions?" | The error path is in the code you read. A reader sees each exit, and the cost is a few lines. |
| talk | "When do you panic?" | A bug, or broken startup config. Then a server recovers at the boundary, logs the stack and returns 500. |
| talk | "What does the client see for an unknown error?" | A fixed message. The real text can hold secrets, so it stays in the log. |
| talk | "How do you retry safely?" | Classify with errors.Is or a Timeout method. Retry only what is temporary and idempotent. |
I define three sentinels in the first minutes and map them in one function, so each handler stays short.
0 of 12 known
Predict the output.
package main import ( "errors" "fmt" ) var ErrNotFound = errors.New("not found") func main() { err := fmt.Errorf("user 7: %w", ErrNotFound) fmt.Println(err) fmt.Println(err == ErrNotFound) fmt.Println(errors.Is(err, ErrNotFound)) }Predict the output.
package main import ( "errors" "fmt" ) var ErrNotFound = errors.New("not found") func main() { a := fmt.Errorf("user 7: %w", ErrNotFound) b := fmt.Errorf("user 7: %v", ErrNotFound) fmt.Println(a.Error() == b.Error()) fmt.Println(errors.Is(a, ErrNotFound)) fmt.Println(errors.Is(b, ErrNotFound)) }Predict the output.
package main import ( "errors" "fmt" "strconv" ) type Timeout interface { error Timeout() bool } type slow struct{} func (slow) Error() string { return "slow" } func (slow) Timeout() bool { return true } func main() { _, err := strconv.Atoi("x") wrapped := fmt.Errorf("port: %w", err) if ne, ok := errors.AsType[*strconv.NumError](wrapped); ok { fmt.Println(ne.Func, ne.Num, ne.Err) } t, ok := errors.AsType[Timeout](fmt.Errorf("call: %w", slow{})) fmt.Println(t.Timeout(), ok) _, ok = errors.AsType[Timeout](wrapped) fmt.Println(ok) }Predict the output.
package main import ( "errors" "fmt" ) func main() { fmt.Println(errors.Join(nil, nil) == nil) a, b := errors.New("a"), errors.New("b") err := errors.Join(a, nil, b) fmt.Printf("%q\n", err.Error()) fmt.Println(errors.Is(err, b)) fmt.Println(errors.Unwrap(err) == nil) }Predict the output.
package main import ( "errors" "fmt" ) var ErrRetry = errors.New("retry") func main() { cause := errors.New("timeout") err := fmt.Errorf("%w: %w", ErrRetry, cause) fmt.Println(err) fmt.Println(errors.Is(err, ErrRetry), errors.Is(err, cause)) fmt.Println(errors.Unwrap(err)) u, ok := err.(interface{ Unwrap() []error }) fmt.Println(len(u.Unwrap()), ok) }Predict the output.
package main import ( "errors" "fmt" ) type Status struct{ Code int } func (s Status) Error() string { return fmt.Sprint("status ", s.Code) } func (s Status) Is(target error) bool { t, ok := target.(Status) return ok && (t.Code == 0 || t.Code == s.Code) } func main() { err := fmt.Errorf("call: %w", Status{503}) fmt.Println(errors.Is(err, Status{503})) fmt.Println(errors.Is(err, Status{404})) fmt.Println(errors.Is(err, Status{})) }Predict the output.
package main import ( "errors" "fmt" ) func main() { var cause error err := fmt.Errorf("load: %w", cause) fmt.Println(err) fmt.Println(err == nil) fmt.Println(errors.Unwrap(err) == nil) }Predict the output.
package main import ( "errors" "fmt" ) func step() (int, error) { return 0, errors.New("failed") } func run() (err error) { if true { n, err := step() fmt.Println(n, err) } return } func main() { fmt.Println(run()) }Predict the output.
package main import "fmt" func helper() any { return recover() } func inner() { defer func() { fmt.Println("helper got:", helper()) }() panic("boom") } func main() { defer func() { fmt.Println("main got:", recover()) }() inner() fmt.Println("not printed") }Predict the output.
package main import ( "errors" "fmt" ) func div(a, b int) (n int, err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("div: %v", r) } }() return a / b, nil } func main() { fmt.Println(div(6, 3)) n, err := div(1, 0) fmt.Println(n, err) var rt interface{ RuntimeError() } fmt.Println(errors.As(err, &rt)) }Predict the output. Main has a deferred recover.
package main import "fmt" func main() { defer func() { fmt.Println("recovered:", recover()) }() go func() { panic("in a goroutine") }() select {} }Predict the output.
package main import ( "context" "errors" "fmt" ) var ErrQuota = errors.New("quota used up") func main() { parent, cancel := context.WithCancelCause(context.Background()) child, stop := context.WithCancel(parent) defer stop() cancel(ErrQuota) cancel(errors.New("second")) fmt.Println(child.Err()) fmt.Println(context.Cause(child)) fmt.Println(errors.Is(child.Err(), context.Canceled)) }
- sentinel
- 1.3 ns with 0 allocations.
- errors.New
- 12.9 ns and 1 allocation.
- wrap
- 148 ns and 2 allocations.
- errors.Is
- 8.7 ns at depth 1; 21.7 ns at depth 5.
- As, AsType
- 114 ns against 13.5 ns.
- panic
- 197 ns, about 124 times a returned error.
Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16, median of 5 interleaved runs of 1 s, on a busy machine. Use these as orders of magnitude.