System Design

G7

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.

Not startedSaved in this browser only.
  1. 1An error is a value. Add what this layer knows, and return it. Handle each error once.
  2. 2Wrap with %w when callers may test the cause. Use %v when the cause is your private detail.
  3. 3Compare with errors.Is and read with errors.As or errors.AsType, never with == or a string match.
  4. 4Panic means a bug or a broken startup. Recover only at a boundary, and turn the panic into an error.
G7
    A

    The trap

    a nil that is not nil
    a nil error pointergo
    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)
    }
    1. 1The concrete return type starts the bug.
    2. 2The nil pointer becomes an interface value with a type word.
    3. 3False, on the path that succeeded. The caller treats success as failure.
    return type of runrecorded outputstatus
    *QueryErrorfalse, *main.QueryError trueNever nil
    errortrue, <nil> falseApproved
    • 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.

    B

    The model: two words

    an error is an interface
    type worddata wordvar err errornilnilerr == nil: trueerr = (*QueryError)(nil)*QueryErrornilerr == nil: false
    • 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.

    C

    Sentinel, typed or opaque

    what a caller can test
    kindtestuse it when
    Sentinelerrors.IsThe caller branches on a condition. It becomes part of your API.
    Typederrors.AsTypeThe caller needs data: a field name, a retry time.
    OpaquenoneThe caller can only log and return. This is the default.
    BehaviourAsType on an interfaceMany 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.

    D

    See it: how errors.Is walks

    the walk is compared with errors.Is
    1. 1*fmt.wrapError: "handler: user 7: not found"
    2. 2err == target: no
    3. 3Unwrap returns one error: go down
    4. 4*fmt.wrapError: "user 7: not found"
    5. 5err == target: no
    6. 6Unwrap returns one error: go down
    7. 7*errors.errorString: "not found"
    8. 8err == target: match
    Step 1 of 8, in chain.
    • %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.

    E

    The rules: the errors package

    recorded in the drill
    you wantwritenotstatus
    Test for a sentinelerrors.Is(err, ErrNotFound)err == ErrNotFoundApproved
    Read a typed errore, ok := errors.AsType[*FieldError](err)err.(*FieldError)Approved
    The same, before Go 1.26var e *FieldError; errors.As(err, &e)errors.As(err, e)Old go.mod
    Report several failureserrors.Join(a, b)A string built by handApproved
    Wrap two causes in one linefmt.Errorf("%w: %w", a, b)Two nested Errorf callsApproved
    Match by contentAn Is method on your typestrings.Contains(err.Error(), ...)Never match text
    Step down one levelAvoid it. Is and As walk for you.errors.Unwrap(err)Single wraps only
    Wrap an error with a value receiverfmt.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.

    F

    Wrap, hide or handle

    one decision per layer
    situationdo thiswhystatus
    A caller may act on the causeWrap with %wIs and As still find it.Approved
    The cause is a detail of your packageUse %v, or return your own sentinelA wrap makes the cause part of your API.Approved
    A storage error crosses into the domainTranslate: no row becomes ErrNotFoundCallers do not import your driver.Approved
    You can recover hereHandle it and return nilHandled means done. Do not also return it.Approved
    You log it and return itChoose oneEach layer logs it, so one failure prints many times.Not approved
    You write "failed to" in the wrapWrite "load user 7: ..."A chain reads better with no repeated words.Not approved
    You write _ = f()Handle it, or log it with a reasonA dropped error is the hardest bug to find.Never swallow
    A loop over items fails on oneJoin, or stop at the firstSay 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.

    G

    Sentinels and a typed error

    tested
    sentinelgo
    // 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")
    )
    1. 1A package variable. Each errors.New call makes a distinct value.
    typedgo
    // 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
    }
    1. 1A pointer receiver, so the pointer is the error. Wrap and test the pointer.
    2. 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.

    H

    Report every bad field

    tested
    validatego
    // 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
    }
    1. 1Interface variables, so a clean field stays a real nil. See panel A.
    2. 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.

    I

    Wrap and translate

    tested
    wrapgo
    // 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
    }
    1. 1The boundary between storage and domain.
    2. 2The wrap adds the id. The domain sentinel replaces the storage one.
    3. 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.

    J

    Hide a cause

    tested
    hidego
    // 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")
    1. 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.

    K

    Do not lose a Close error

    tested on four paths
    closego
    // 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
    }
    1. 1A named result, so the defer can change what the function returns.
    2. 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.

    L

    When a panic is correct

    the rules, and a tested example
    situationusestatus
    Bad input, a missing row, a network failureReturn an errorApproved
    A regular expression or template in the source is wrongPanic at startupApproved
    A state the code proves cannot happenPanic: it is a bugApproved
    One request crashes in a serverRecover at the boundaryBoundary only
    Panic and recover as control flow inside a packageReturn an errorInside one parser only
    A panic crosses a package APIReturn an errorNot approved
    A panic in a goroutine you startedRecover in that goroutinemain cannot catch it
    mustgo
    // 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-]+$`))
    1. 1The input is in the source, so a failure is a bug. The program must not start.
    2. 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.

    M

    Recover at a boundary

    tested
    protectgo
    // 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()
    }
    1. 1Works only when the deferred function calls it directly, in the panicking goroutine.
    2. 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.

    N

    Say why it stopped

    tested on a fake clock
    causego
    // 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
    }
    1. 1Go 1.21. Cause returns this error when the timer fires.
    2. 2Go 1.20. It returns the parent cause if the parent ended first.
    3. 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.

    O

    Errors at the API boundary

    each row is a call to the function below
    the errorstatusthe client gets
    user 7: not found404{"error":"user 7: not found"}
    create: conflict409{"error":"create: conflict"}
    signup: age: must not be negative400{"error":"invalid","field":"age"}
    parse: invalid400{"error":"parse: invalid"}
    fetch: backend too slow504{"error":"fetch: backend too slow"}
    context canceled499{"error":"context canceled"}
    dial db: connection refused500{"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.

    P

    The mapping

    tested
    failurego
    // 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()}
    }
    1. 1Before the switch, because a FieldError also matches ErrInvalid.
    2. 2The one place where an unknown error is logged. The handler layers do not log it.
    3. 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.

    Q

    One exit

    tested
    routego
    // 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
        }
      })
    }
    1. 1A copy per request. status is shared by every request on this route.
    2. 2A panic becomes a 500 for this request, and the server keeps running.
    3. 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.

    R

    New in recent Go

    checked against each release's notes
    sincewhat changedwhat it means here
    1.13fmt.Errorf %w. errors.Unwrap, Is and As.The base of this sheet.
    1.20errors.Join. Multiple %w. Unwrap() []error. context.WithCancelCause and context.Cause.An error can be a tree, as panel D shows.
    1.21context.WithDeadlineCause and WithTimeoutCause. errors.ErrUnsupported. panic(nil) becomes *runtime.PanicNilError.A non-nil recover result always means a panic.
    1.25A recovered and repeated panic prints [recovered, repanicked] and does not repeat the text.Crash logs from panel M are shorter.
    1.26errors.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.27go 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.
    S

    In the round

    45 minutes of build, 45 minutes of talk
    whenthe momentwhat to do or say
    buildYou start the service.Write ErrNotFound, ErrConflict and ErrInvalid first. The store and the handler share them.
    buildA handler needs a status code.Do not choose it in the handler. Add a case to failure, with a row in a table test.
    buildA 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.

    T

    Drill

    each answer is the output of a real run

    0 of 12 known

    1. 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))
      }
    2. 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))
      }
    3. 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)
      }
    4. 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)
      }
    5. 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)
      }
    6. 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{}))
      }
    7. 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)
      }
    8. 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())
      }
    9. 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")
      }
    10. 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))
      }
    11. 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 {}
      }
    12. 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))
      }
    U

    Numbers to say

    measured with testing.B
    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.