Zero2Scale

Error handling bugs: checking an error is not handling it

23 min read


An editor app has a save-draft function. Autosave calls it every minute.

type Draft struct {
	ID             string  `json:"id"`
	Body           string  `json:"body"`
	WordsPerMinute float64 `json:"words_per_minute"`
}

func NewDraft(id, body string, minutes float64) Draft {
	words := len(strings.Fields(body))
	return Draft{ID: id, Body: body, WordsPerMinute: float64(words) / minutes}
}

func (s Store) SaveDraft(d Draft) {
	b, err := json.Marshal(d)
	if err != nil {
		log.Println("marshal draft:", err)
	}
	if err := os.WriteFile(s.path(d.ID), b, 0o644); err != nil {
		log.Println("save draft:", err)
	}
}

The code checks every error and logs every error. It looks careful. One day a user opens a file they spent three hours writing, and autosave runs at once, so minutes is 0.

after the first save: 128 bytes
marshal draft: json: unsupported value: +Inf
after the second save: 0 bytes

float64(words) / 0 is +Inf, and encoding/json cannot encode it. json.Marshal returns an error and b is nil. The code logs the error and carries on. os.WriteFile writes nil over the old file. Three hours of writing are gone, and the log records every step.

The bug map puts this bug in group 3, error handling. The previous article ended with a Google Cloud outage caused by code without proper error handling. This article answers the next question. If the code checked the error and logged it, why was the data still lost?

Checking an error is not handling it

In 2014, Ding Yuan and a team from the University of Toronto studied 198 user-reported failures in Cassandra, HBase, HDFS, Hadoop MapReduce and Redis. Of these, 48 were catastrophic, which means they affected all or most users. They found:

  • 92% of the catastrophic failures came from incorrect handling of non-fatal errors that the software had signaled explicitly.
  • The developers had checked the error in every case but one. The problem was not a missing check.
  • 35% came from three trivial mistakes: the handler ignored the error (25%), the handler caught an overly general exception and shut down the cluster (8%), or the handler contained only a "TODO" comment (2%).
  • 58% could easily have been detected by a test that ran the error handling code at least once.

To me, the most interesting part is the definition of "ignored the error". The study counts a handler that only logs as ignoring the error. That is exactly what SaveDraft does.

Dave Cheney wrote in a 2016 blog post that handling an error means inspecting the error value and making a decision. If you make less than one decision, you ignore the error. If you make more than one decision for a single error, that is also a problem.

The short answer of this article: every error needs exactly one decision, made by code that knows enough to make it, and a test must run that decision before production does.

There are only a few decisions to choose from:

  1. Return the error to the caller, with a note on what you were doing.
  2. Retry, if repeating the work is safe.
  3. Fall back, for example read from the source when the cache fails.
  4. Undo the work that is already done.
  5. Stop the program, when carrying on would cause more damage.

Logging is not on the list. A log line records a decision. It is not the decision. All of group 3 is about decisions that are missing, made twice, made with the wrong information, made in the wrong place, or never run. The rest of the article looks at each one.

Log-only means "carry on as if it worked"

SaveDraft did make a decision. It decided, without noticing, to carry on as if json.Marshal had worked. Yuan's study has the same case in HBase. During a region split, the file system returned an unexpected error. The handler logged "split failed" and carried on. The old region was already removed, but the new regions were never created, so data was lost. The real fix was to retry the split in the handler.

SaveDraft does not know what should happen next. So it should choose decision 1 and return the error.

func (s Store) SaveDraft(d Draft) error {
	b, err := json.Marshal(d)
	if err != nil {
		return fmt.Errorf("encoding draft %s: %w", d.ID, err)
	}
	if err := os.WriteFile(s.path(d.ID), b, 0o644); err != nil {
		return fmt.Errorf("writing draft %s: %w", d.ID, err)
	}
	return nil
}

Now the caller decides. The editor's handler knows a user is waiting. It shows "save failed" and keeps the text on screen. The old draft on disk is not touched.

The contact form on this site works the same way. If Mailer.Send in internal/shell/web/contact.go fails, the handler responds with 503 and a message that sending failed, and the form still holds everything the user typed. contact_test.go has a case named "delivery failure keeps text" that simulates an SMTP outage to check this.

The opposite mistake is to decide twice, for example to log the error and also return it. Every layer that does this logs the same error again. Cheney describes the result: a stack of duplicate log lines, while the top of the program gets the original error without any context. That is why this repository's AGENTS.md says handlers just return err. handleError in internal/shell/web/respond.go is the one place that turns errors into HTTP responses and logs them.

// handleError is the single place where errors become HTTP responses.
func (s *server) handleError(c fiber.Ctx, err error) error {
	status := fiber.StatusInternalServerError
	var fe *fiber.Error
	switch {
	case errors.Is(err, content.ErrNotFound), errors.Is(err, listing.ErrPageOutOfRange):
		status = fiber.StatusNotFound
	case errors.As(err, &fe):
		status = fe.Code
	}

	if status >= 500 {
		s.Log.ErrorContext(c.Context(), "request failed",
			"request_id", requestid.FromContext(c), "path", c.Path(), "err", err)
	}
	// ...
}

One error gives one log line, with the request ID and the path.

An error must say what the code was doing

If you return the error unchanged, the code that decides gets too little information. Try to load the metadata of three posts, where one file was cut off in the middle.

func decodeBare(raw string) (Meta, error) {
	var m Meta
	err := json.NewDecoder(strings.NewReader(raw)).Decode(&m)
	return m, err // returns the error unchanged
}

func decode(raw string) (Meta, error) {
	var m Meta
	if err := json.NewDecoder(strings.NewReader(raw)).Decode(&m); err != nil {
		return Meta{}, fmt.Errorf("decoding metadata: %w", err)
	}
	return m, nil
}

// loadAll calls decode for each file and adds the slug to the error:
// fmt.Errorf("loading post %s: %w", slug, err)
bare:    unexpected EOF
wrapped: loading post why-bugs-recur: decoding metadata: unexpected EOF

The first line only says that something ended too early. The second line says which file failed and at which step. Each layer adds what it knows. decode knows it was decoding metadata. loadAll knows which post it was loading. That is why this repository's AGENTS.md says to wrap errors with fmt.Errorf("doing x: %w", err).

After you wrap, compare with errors.Is

Adding context can cause another bug if a caller compares errors with ==.

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

// New version: someone added context to the error, which is a good change
func postV2(slug string) (string, error) {
	p, ok := posts[slug]
	if !ok {
		return "", fmt.Errorf("loading post %q: %w", slug, ErrNotFound)
	}
	return p, nil
}

func statusEq(err error) int {
	if err == ErrNotFound { // compares with ==
		return 404
	}
	return 500
}
v1, ==:         404
v2, ==:         500
v2, errors.Is:  404

Nobody touched the handler, but every missing post is now a 500. The dashboard turns red and the on-call engineer gets paged, all because of a good change in another file. err is now a new error that wraps ErrNotFound. == compares only the outer error. errors.Is walks the whole chain, and errors.As finds an error by its type.

The errorlint linter, which this repository enables, catches it:

is/main.go:31:5: comparing with == will fail on wrapped errors. Use errors.Is to check for a specific error (errorlint)

The 2019 Go blog post that introduced %w has a warning worth remembering. Wrapping an error makes the inner error part of your API. Callers start to write errors.Is(err, sql.ErrNoRows), and then you cannot switch databases without breaking them. If you do not want callers to depend on the inner error, use %v, which keeps the message but not the error value. Or translate it into your own package's sentinel, such as content.ErrNotFound.

The code that knows enough makes the decision

The same error deserves different decisions, depending on who holds it. A Redis timeout in the cache is a small problem. But if it travels up to the handler and nobody decides on the way, the handler sees only "an error" and responds with 500. Redis goes down, and the whole site goes down with it.

In this repository, the layer that knows Redis is only a cache is internal/shell/cache (ADR 0004). So it makes the decision, and the decision is to fall back.

b, err := c.rdb.Get(getCtx, key).Bytes()
cancel()
switch {
case err == nil:
	return b, nil
case !errors.Is(err, redis.Nil):
	c.log.WarnContext(ctx, "cache get failed", "key", key, "err", err)
}

b, err = compute() // read from the source instead
if err != nil {
	return nil, err // a source error goes up, because the cache does not know what to do
}

This code also logs and carries on, like SaveDraft. The difference is that carrying on is a deliberate decision. The package comment and the ADR state it, and tests confirm it. TestGetOrCompute_RedisDownDegrades closes miniredis before the call and checks that the value is still correct. TestPagesAreCachedInRedis closes Redis partway through and checks that the post page still returns 200.

The opposite mistake is a decision that is too broad, made with too little knowledge. Yuan describes an HDFS datanode registering with the namenode. The code meant to call System.exit(-1) on IncorrectVersionException, but it caught Throwable, which includes everything. When a glitch in the namenode threw a RemoteException, every datanode shut itself down at the same time. In Go, the same pattern is log.Fatal or panic inside a library. The library decides for the whole program, but it does not know what the program is doing.

The Google Cloud report on 12 June 2025, which the previous article described, says the change "did not have appropriate error handling". So a null pointer crashed the binary, although one bad policy should not stop the whole service. One of Google's commitments is to split Service Control into isolated parts that fail open. Fail open means that when a policy check cannot run, the request goes through instead of everything stopping. Whether to fail open or fail closed depends on the job. Most authorization checks should fail closed. The point is that someone must make this decision in advance, instead of letting a null pointer make it.

Half-done work must be undone

Some work has several steps. If step 2 fails, returning the error is not enough, because step 1 already happened.

func Transfer(l *Ledger, from, to string, amt int64) error {
	if err := l.Debit(from, amt); err != nil {
		return fmt.Errorf("transfer: %w", err)
	}
	if err := l.Credit(to, amt); err != nil {
		return fmt.Errorf("transfer: %w", err) // the money already left from
	}
	return nil
}
total before: 100000
Transfer: transfer: crediting bob: account is frozen
total after:  60000 map[alice:60000 bob:0]

The error is returned correctly, with full context, but 400 baht has left the system. The HBase region in the earlier section failed the same way: the old region was removed, but the new one was never finished. Even os.WriteFile in SaveDraft has this problem. The Go documentation says it truncates the file before writing, and a failure in the middle can leave the file partly written. The usual fix is to write to a temporary file first and then rename it over the old one.

There are two levels of fix. The first is to finish every decision before touching real data, as in Functional Core, Imperative Shell.

// PlanTransfer is a pure function. It checks every condition first, then returns the full set of new balances.
// If any check fails, nothing changes.
func PlanTransfer(bal map[string]int64, frozen map[string]bool, from, to string, amt int64) (map[string]int64, error) {
	switch {
	case frozen[from]:
		return nil, fmt.Errorf("debiting %s: %w", from, ErrFrozen)
	case frozen[to]:
		return nil, fmt.Errorf("crediting %s: %w", to, ErrFrozen)
	case bal[from] < amt:
		return nil, fmt.Errorf("debiting %s: %w", from, ErrInsufficient)
	}
	next := maps.Clone(bal)
	next[from] -= amt
	next[to] += amt
	return next, nil
}
PlanTransfer: crediting bob: account is frozen
total after:  100000 map[alice:100000 bob:0]

The second level is to make all the writes happen together or not at all. That is a database transaction.

tx, err := db.BeginTx(ctx, nil)
if err != nil {
	return fmt.Errorf("transfer: begin: %w", err)
}
// After a successful Commit, Rollback returns ErrTxDone, which needs no action
defer func() { _ = tx.Rollback() }()

if _, err := tx.ExecContext(ctx, `UPDATE accounts SET balance = balance - $1 WHERE id = $2`, amt, from); err != nil {
	return fmt.Errorf("transfer: debit %s: %w", from, err)
}
if _, err := tx.ExecContext(ctx, `UPDATE accounts SET balance = balance + $1 WHERE id = $2`, amt, to); err != nil {
	return fmt.Errorf("transfer: credit %s: %w", to, err)
}
if err := tx.Commit(); err != nil {
	return fmt.Errorf("transfer: commit: %w", err)
}

Every return before Commit rolls back automatically. Note the _ = tx.Rollback(). If you write a bare defer tx.Rollback(), errcheck reports Error return value of tx.Rollback is not checked. Writing _ = does not just make the error disappear. It is a decision written where everyone can see it, and the comment gives the reason.

Retry only work that gives the same result when repeated

Retrying sounds safe. But a 2017 Stripe blog post points out that a network request can fail at three points: before it reaches the server, while the server works, or after the server finishes but the response is lost on the way back. In the last case, the client does not know whether the work succeeded, so it does not know whether a retry is safe.

func pay(g *Gateway, key string, amt int64) (string, error) {
	var err error
	for range 3 {
		var id string
		if id, err = g.Charge(key, amt); err == nil {
			return id, nil
		}
	}
	return "", fmt.Errorf("paying: %w", err)
}

Let Gateway simulate a network that drops the first response, after the charge has already happened.

no key:   ch_2 <nil> charges = [35000 35000]
with key: ch_1 <nil> charges = [35000]

There is not a single error, but the customer is charged 350 baht twice. The fix is idempotency: repeating the same work gives the same result as doing it once. The client creates one key per piece of work and sends the same key with every retry. A server that has already seen the key returns the saved result and does not charge again. Stripe accepts this key in the Idempotency-Key header. A key can be up to 255 characters long. In API v1, Stripe saves the status code and body of the first request, including 500 errors. If a request reuses a key with different parameters, Stripe returns an error.

Retries have another problem, even when the work is idempotent. Marc Brooker of AWS writes that retries are "selfish": a client spends more of the server's time to raise its own chance of success. If a call goes through five layers of services and each layer tries three times, the database at the bottom gets 3^5 = 243 times the load, on a day when it is already struggling. His advice is to retry at one point in the stack, with exponential backoff and jitter. That means you wait longer after each failed try, and you add a random amount to the wait, so that all clients do not come back at the same moment. The Google Cloud report mentions this too. When Service Control restarted, the tasks starting at the same time overloaded the Spanner table it depends on, because it had no randomized exponential backoff.

Run the error path before your users do

Why do bugs in this group reach production so often? Because error handling code almost never runs. Most tests exercise the path where everything works. The if err != nil branch runs for the first time when the system is at its worst.

Yuan's study found that 23% of the catastrophic failures would have been exposed by any test that ran every statement in the error handling code, because those blocks were wrong as a whole. In one MapReduce case, the handler had only a // TODO comment and a log line. It ran very rarely, but when it did, it took down a production cluster of 4,000 nodes. The study suggests working bottom-up: start from each handler and build a test that reaches it.

The fixed SaveDraft has such a test:

func TestSaveDraftFailureKeepsOldDraft(t *testing.T) {
	s := Store{dir: t.TempDir()}
	if err := s.SaveDraft(NewDraft("post-1", "three hours of writing", 180)); err != nil {
		t.Fatal(err)
	}
	before, _ := os.ReadFile(s.path("post-1"))

	err := s.SaveDraft(NewDraft("post-1", "three hours of writing", 0)) // force the encoding to fail
	if err == nil {
		t.Fatal("SaveDraft succeeded; want an error")
	}
	t.Log(err)

	after, _ := os.ReadFile(s.path("post-1"))
	if string(after) != string(before) {
		t.Fatalf("draft changed after a failed save: %q", after)
	}
}
=== RUN   TestSaveDraftFailureKeepsOldDraft
    draft_test.go:19: encoding draft post-1: json: unsupported value: +Inf
--- PASS: TestSaveDraftFailureKeepsOldDraft (0.00s)

This test does not only ask "did we get an error?". It asks "after the error, is the old data still there?", which is what the user cares about. The Redis and SMTP tests in this repository do the same thing. They break a dependency on purpose and then check what the user sees.

Turn the bug that bit you into a rule

Linters catch the first two ways of losing an error, but not the third.

func loadIgnored(b []byte) Settings {
	var s Settings
	json.Unmarshal(b, &s) // way 1: never looks at the error
	return s
}

func loadSwallowed(path string) error {
	b, err := os.ReadFile(path)
	if err != nil {
		return nil // way 2: checks it, then returns nil
	}
	_ = b
	return nil
}

func loadLogged(b []byte) Settings {
	var s Settings
	if err := json.Unmarshal(b, &s); err != nil {
		log.Println("load settings:", err) // way 3: logs it, then carries on
	}
	return s
}
lints/main.go:13:16: Error return value of `json.Unmarshal` is not checked (errcheck)
lints/main.go:20:3: error is not nil (line 18) but it returns nil (nilerr)

golangci-lint enables errcheck by default. You must turn on nilerr yourself. Way 3 passes every linter, because the error is checked and used. Way 3 is the one that lost the draft, and it is the one Yuan's study also counts as ignoring the error.

One more thing to know. This repository enables golangci-lint's std-error-handling preset, which tells errcheck not to report Close, Flush, os.Remove and the print functions. That is usually a fair trade, but Close on a file you just wrote is an exception. The close(2) man page warns that errors from earlier writes may be reported only at close, and that not checking can lose data silently, especially on NFS and with disk quotas.

This repository already has the Opengrep rule empty-error-branch in .opengrep/agent-hygiene.yaml, for an empty if err != nil {}. Way 3 can become a rule in the same way, as the Opengrep article explains.

rules:
  - id: log-only-error-branch
    languages: [go]
    severity: WARNING
    message: >-
      `$ERR` is logged and then the code carries on as if it succeeded. A log
      line records a decision, it is not one. Return the error with context, or
      write the decision in code (fall back, retry, skip) and say why.
    patterns:
      - pattern-either:
          - pattern: |
              if $ERR != nil {
                $LOGF(...)
              }
          - pattern: |
              if $ERR := $E; $ERR != nil {
                $LOGF(...)
              }
      - metavariable-regex:
          metavariable: $LOGF
          regex: (?i)^(.*\.)?(log|logger)\.(print|printf|println|debug|info|warn|error)(context)?$

The rule looks for an error branch that contains only one log call. A branch that logs and then calls continue or return does not count, because the decision is in the code. One trap: metavariable-regex always matches from the start of the string. My first version used (^|\.)log. It matched log.Println but not s.log.Error, so the regex has to start with ^(.*\.)?. The fixture file has two // ruleid: lines and two // ok: lines. opengrep test reports 1/1: ✓ All tests passed. The rule was run with Opengrep 1.26.0.

Run against internal and cmd in this repository, the rule finds two places:

cmd/server/main.go
  162┆ if err := rdb.Ping(ctx).Err(); err != nil {
  163┆    log.Warn("redis unreachable; serving uncached until it recovers", "err", err)
  164┆ }
internal/shell/cache/cache.go
   61┆ if err := c.rdb.Set(setCtx, key, b, ttl).Err(); err != nil {
   62┆    c.log.WarnContext(ctx, "cache set failed", "key", key, "err", err)
   63┆ }

Both are deliberate. Redis is only a cache, so carrying on without it is the right decision. A pattern rule cannot tell a deliberate log from a forgotten one, but it makes the author say which it is. AGENTS.md requires a reason next to every nosemgrep comment and a reviewer's agreement. A decision that was hidden in a log line becomes a line that people can read and review.

Yuan's study did the same thing in 2014. The team built a tool named Aspirator from three simple rules: a handler that does nothing, a handler that catches broadly and aborts, and a handler with TODO or FIXME. Run on 9 distributed systems, Aspirator found 143 bugs and bad practices that the projects' developers confirmed or fixed. The team estimates that over 30% of the catastrophic failures in the study would have been prevented if developers had used Aspirator and fixed what it found.

Agents silence errors to make tests pass

When you tell an agent to "make the build pass" or "make the tests pass", the smallest diff often silences an error. Examples are _ = in front of a call it does not want to check, return nil in an error branch, logging and carrying on, a recover() that swallows every panic, or a retry wrapped around everything. Each one turns the tests green. Each one is a decision that nobody meant to make. That is why this repository keeps the empty-error-branch rule in a file named agent-hygiene.yaml.

When you read a diff that an agent wrote, as the article on reading code suggests, stop at every if err != nil and ask three questions:

  1. What does this branch decide: return, retry, fall back, undo or stop?
  2. Does this code know enough to decide, or should it pass the error to a layer that does?
  3. Is there a test that runs this branch?

If you cannot answer the first question, the branch ignores the error, whether or not it has a log line.

A table to keep

Bug The wrong decision Why it recurs What helps
Never looking at the error No decision It compiles, and the normal path still works errcheck
Checking, then return nil Decides that it worked The smallest diff that makes tests pass nilerr
Logging, then carrying on Decides that it worked, with evidence in the log It looks careful An Opengrep rule and tests that fail on purpose
Logging, then returning Decides twice Every layer wants to help Log in one place, such as handleError
An error without context The decider has too little information return err is the shortest line fmt.Errorf("doing x: %w", err)
Comparing with == Uses the wrong value It worked until someone wrapped the error errors.Is, errors.As and errorlint
Deciding in the wrong layer Code that does not know makes the decision Passing it up forever, or catching broadly just in case Let the layer that knows decide, and test with the dependency down
Half-done work Returns the error, but does not undo Step 2 rarely fails Decide everything in a pure function, then write in a transaction
Unsafe retry Repeats work that cannot be repeated The client does not know whether the first request worked An idempotency key, retry at one point, and backoff with jitter

What to do differently

Every time you write if err != nil, be able to say what the branch decides and who should make that decision. If the answer is "log it for now", ask what the program does after the log line, and whether that is safe. Every time you retry, ask what happens if the first try already succeeded. And every important error branch should have a test that runs it at least once, before a user runs it for the first time.

The next article in this series looks at group 4, resources and memory: file handles that are never closed, goroutines that never end, and caches that grow without limit. Many of these start in an error branch that returns before it releases a resource.

References