Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 147 ยท Errors

Error Handling Patterns

Practical Go error handling patterns - handle or return but never both, log once, retry with backoff, collect errors from goroutines, clean up with defer, Must helpers and an error-collecting writer.

You now know the mechanics: errors are values, they can be wrapped, described by custom types and, for real bugs, escalated with panic. What remains is the craft of using them well in real programs. Where should an error be logged? When is retrying sensible? How do you report failures from ten goroutines? How do you keep a function that makes twenty fallible calls readable?

This lesson collects the patterns that experienced Go developers reach for again and again. None of them is new syntax; they are habits that make error handling consistent, cheap to read and easy to debug.

Handle an error once

Every error should be handled exactly once. "Handled" means one of: you recovered from it, you returned it to your caller, or you reported it (logged it, showed it to the user, exited). The classic mistake is to do two of those at the same time, usually log and return:

Go Log and return: the same failure logged three times

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The same problem produces three log lines, with no extra information. In a busy service these duplicates bury the signal and make it unclear where the problem really occurred. The fix: lower layers add context and return; only the top layer (usually main, a request handler or a job runner) logs:

Go Wrap with context, log once at the top

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The single line error: handle request: load user 7: connection reset has the whole story, each layer contributing what only it knows. There are legitimate exceptions: if you recover from an error and carry on, log it at that point as a warning, because the caller will never see it.

A main that returns errors

main cannot return an error, so the standard shape moves the program into a run function. All defers inside run complete before the process exits, and the error-to-exit-code translation happens in exactly one place:

Go main calls run and decides the exit status

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

In a real program the end of main is os.Exit(exitCode(err)). Because run returns normally, cleanup in deferred calls happens first (compare panic and recover, where os.Exit skips deferred calls).

Retry with backoff

Some failures are transient: a timeout, a rate limit, a dropped connection. Retrying often succeeds, but a naive loop hammers a struggling server. Good retry code has four ingredients: a maximum number of attempts, a delay that grows (exponential backoff), a way to recognize errors that are not worth retrying, and the final error should explain what happened.

Go Retry with exponential backoff and a permanent error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The delays printed (100ms, 200ms) are what a real client would wait; the demo divides the sleep by 1000 to run quickly. Real code usually adds jitter (a random fraction of the delay) so that many clients do not retry in lockstep, and respects a context.Context so that a cancelled request stops retrying (see Context). Only retry operations that are idempotent, meaning safe to run twice: reading data, yes; charging a credit card, only with an idempotency key.

Cleanup with defer, and errors from Close

defer is the tool for cleanup, but it hides one question: what if the cleanup call itself fails? For files opened for reading, ignoring Close is fine. For anything you wrote to, Close can report that buffered data did not make it, so the error matters. A named result and a deferred function can fold it into the function's result:

Go Not losing the error from Close

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

For a successful Write, the caller still learns that closing failed. For a failed one, both messages are kept. A shorter version for the common case is if cerr := f.Close(); cerr != nil && err == nil { err = cerr }, which keeps only the first error.

Collecting errors from goroutines

When work is split across goroutines, the function that started them still needs to know whether they succeeded. A goroutine cannot return an error to its starter; the simplest reliable pattern is for each worker to write into its own slot of a slice, and for the caller to wait and then combine:

Go Errors from concurrent workers, one slot each

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Because every goroutine touches a different element and wg.Wait() establishes a happens-before relationship, there is no data race and the output order is deterministic. If you need to cancel the remaining work after the first failure, the pattern grows into an "error group" with a context; the golang.org/x/sync/errgroup package implements it, and Concurrency Patterns builds the idea with the standard library alone. Also remember to put a recover in goroutines that might panic, as explained in panic and recover.

Reducing if err != nil: errors are values

Because errors are values, you can program with them. The best-known trick is Rob Pike's observation that when many consecutive calls can fail, you can store the first error in a small type and skip all later operations:

Go An error-collecting writer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The code that uses the writer has no if after each call; there is a single check at the end. The standard library does the same: bufio.Writer remembers the first write error and returns it from Flush, and bufio.Scanner ends iteration and reports the cause from scanner.Err(). Use this pattern when the operations are the same kind, and failing at step 2 means steps 3 to 4 are pointless. Do not use it to hide errors that need different handling.

Another way to shorten repeated checks is a small helper for a fixed, simple reaction, such as check(err) in a throwaway script or a test helper that calls t.Fatal. In production code, prefer explicit checks that add context; if err != nil { return err } is cheap to read.

Common mistakes

Shadowing err

The short declaration := creates a new variable if any name on the left is new, and inside a nested block even an existing name can be shadowed. This compiles, but silently throws an error away:

Go A shadowed err loses the error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The separate shadow analyzer for go vet, and linters such as golangci-lint, can find these. The easiest defence is to keep functions short and to declare variables near their use.

Other pitfalls to avoid

  • Swallowing errors with _ when a failure matters, or an empty if err != nil {} block.
  • Using the result when err != nil. Unless the function documents otherwise (for example io.Reader.Read can return both data and an error), assume the value is meaningless.
  • Comparing error strings or checking types with a type assertion (err.(*MyErr)) instead of errors.Is / errors.As, which also see wrapped errors.
  • Panicking for ordinary failures such as bad user input or missing files.
  • Overly vague context, like fmt.Errorf("error: %w", err). Say what you were doing.
  • Returning a concrete error type instead of error, which invites the typed nil trap (Custom Error Types).

A checklist

  1. Check every returned error, or ignore it explicitly with a reason.
  2. Add context with %w and short, lower-case descriptions of the operation.
  3. Handle each error once: recover, return, or report.
  4. Log at the top of the call chain, not at every layer.
  5. Use errors.Is/errors.As, never string matching.
  6. Keep cleanup in defer, and keep Close errors for written files.
  7. Collect errors from goroutines explicitly, and recover from panics at goroutine boundaries.
  8. Retry only transient, idempotent operations, with a limit and backoff.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is logging an error and then returning it considered a bad pattern?

    Each layer that logs and returns produces another log line for the same failure. Handle an error once: lower layers add context and return, and the top layer logs.
  2. 2. What is the purpose of the run() error pattern?

    main cannot return an error. A run function returns normally, so its defers run, and main then decides what to print and which status to pass to os.Exit.
  3. 3. Which operations are safe to retry automatically?

    Retrying transient failures of operations that can be safely repeated is sensible. Permanent errors such as invalid input will fail again.
  4. 4. In the errWriter pattern, what happens to calls after the first failure?

    The writer remembers the first error and returns early from later calls, so the caller needs a single check at the end.
  5. 5. What goes wrong in n, err := step() inside an if block when an outer err exists?

    Inside a nested block, := declares new variables, including a new err. The outer err is untouched, so the function may return nil after a failure.

Summary

  • Handle each error exactly once: recover, return (with context), or report. Log at the top of the call chain.
  • Put the program in run() error and translate errors into exit codes in main, after deferred cleanup has run.
  • Retry only transient, idempotent failures, with a maximum, exponential backoff, jitter and a stop for permanent errors; combine the attempt errors with errors.Join.
  • Keep the error from Close when you wrote to a file, using a named result or errors.Join in a deferred function.
  • Collect errors from goroutines in per-worker slots (or an error group) and recover from panics inside them.
  • Errors are values: an errWriter-style type removes repetitive checks when later steps depend on earlier ones.
  • Watch out for shadowed err, ignored results, string matching and panicking for ordinary failures.

Next: Goroutines starts the Concurrency chapter, where Go's lightweight threads run code at the same time.