My account

Errors in Go

In Go an error is a normal value that a function returns. Each layer either sends the error up with more context, or handles it once and only once. If you understand wrapping with %w, the errors.Is and errors.As functions, sentinel errors and custom error types, the typed nil trap, and panic versus error, you can answer most interview questions.

Not reviewedWritten with AI helpReading time: 20 minOnline shop exampleGo 1.25 code

Author: bezzad

Contents

The problem: an order service that loses its errors

The order service of our shop is written in Go. It handles orders, payments and stock. This week we have four bug reports:

  1. In the logs we only see one line: “sql: no rows in result set”. We do not know which order or which query.
  2. The same error appears three times in the logs. Every layer logged it and then sent it up.
  3. When an order does not exist, the API returns 500 instead of 404. Someone compared the error with ==, but the error was wrapped on the way.
  4. All payments are reported as failed, even the successful ones. The payment function returns a nil pointer of its own error type.

We have one more bug. A panic in a background goroutine shut down the whole server, even though our middleware has recover.

All of these come from using errors the wrong way. In this lesson we see how errors work in Go, and what interviewers ask about them.

An error is a value

Go has no exceptions for normal errors. An error is a value that a function returns, usually as its last result. The error type is a very small interface:

type error interface {
	Error() string
}

Any type with an Error method is an error. The caller must check the error right away:

o, err := repo.Find(ctx, id)
if err != nil {
	return err
}
// here o is valid
  1. The main path of the code stays on the left, without extra indentation. Each error returns early.
  2. Because an error is a value, you can keep it in a variable, compare it, collect it in a list, or wrap it with more context.
  3. When the error is not nil, do not trust the other results. Usually they are the zero value of their type.

There are also two small rules for the error text. It starts with a small letter and has no period or exclamation mark at the end. The reason: errors are joined one after another into one long sentence.

Adding context with fmt.Errorf and %w

The first bug in this lesson was an error with no context. The fix: each layer says what it was doing. The fmt.Errorf function with the %w verb wraps the old error inside a new one:

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

func (r *Repo) Find(ctx context.Context, id string) (Order, error) {
	const q = "SELECT id, status FROM orders WHERE id = $1"
	var o Order
	err := r.db.QueryRowContext(ctx, q, id).
		Scan(&o.ID, &o.Status)
	if errors.Is(err, sql.ErrNoRows) {
		return Order{}, ErrNotFound
	}
	if err != nil {
		return Order{}, fmt.Errorf("query order: %w", err)
	}
	return o, nil
}

func (s *Service) Pay(ctx context.Context, id string) error {
	o, err := s.repo.Find(ctx, id)
	if err != nil {
		return fmt.Errorf("pay order %s: %w", id, err)
	}
	// charge the customer ...
	return nil
}

Now the error text is “pay order 42: order not found”. Each layer added a piece to the front.

  1. The %w verb keeps the original error. The new error has an Unwrap method that returns the inner error.
  2. The %v verb only copies the text of the original error. The chain is cut, and the original error can not be found anymore.
  3. The repository turns sql.ErrNoRows into its own error, ErrNotFound. Higher layers do not need to know the database/sql package.
When should I use %v? When you wrap an inner error with %w, that error becomes part of your API. Callers start to depend on it, and later you can not change it. If you do not want inner details to leak out, like the error of a database driver, use %v or return your own error.

The errors.Is and errors.As functions

When an error is wrapped, comparing with == does not work anymore. The outer error is a new value. This is the third bug of the lesson.

err := fmt.Errorf("pay order 42: %w", ErrNotFound)

fmt.Println(err == ErrNotFound)          // false
fmt.Println(errors.Is(err, ErrNotFound)) // true

The errors.Is function starts at the outer error and goes down layer by layer with Unwrap. If one of the layers equals the target, it returns true.

The error chainWhat errors.Is doescheckout: pay order 42: order not foundcheckout layer, with %wpay order 42: order not foundservice layer, with %worder not foundsentinel ErrNotFound in the repositoryUnwrapUnwrap1. Equal? No2. Equal? No3. Equal? Yes, true
Each layer adds context to the error and wraps the previous one. The errors.Is function starts at the top and goes down with Unwrap until it finds the sentinel error.

The errors.As function does the same for an error type. It finds the first error in the chain with the wanted type and puts it into your variable:

type PaymentError struct {
	Code  string // for example "card_declined"
	Retry bool
}

func (e *PaymentError) Error() string {
	return "payment failed: " + e.Code
}

func shouldRetry(err error) bool {
	var pe *PaymentError
	return errors.As(err, &pe) && pe.Retry
}
  1. The second argument of errors.As must be a non-nil pointer. If it is not, the function panics. The go vet tool finds this mistake.
  2. Here the Error method is defined on the pointer. So the error type is a pointer to PaymentError, and the variable pe must have the same type.
  3. Both functions also search errors made with errors.Join or with several %w verbs. These errors make a tree, not a simple chain.

Go 1.26 added a new function, errors.AsType. It is a generic version of errors.As. It takes the type as a type parameter, needs no separate variable, and catches a wrong type at compile time:

// Go 1.26 and later
if pe, ok := errors.AsType[*PaymentError](err); ok {
	log.Println("payment code:", pe.Code)
}

Sentinel error or custom error type

So that the caller can decide what to do, we have two main ways:

Way Example When it fits Check with
Sentinel error the ErrNotFound variable or io.EOF Only what happened matters. No extra data is needed. the errors.Is function
Custom error type the PaymentError type The caller needs data, like the payment code or whether to retry. the errors.As function
Opaque error fmt.Errorf with %v The caller only needs to know that an error happened. only err != nil
  1. A sentinel error is a package-level variable made with errors.New. By convention its name starts with Err.
  2. A custom error type is a struct with an Error method. By convention its name ends with Error.
  3. Both are part of your package’s public API. Export only what callers really need.

The HTTP layer can now turn each error into the right status code. This is the only place where the error is logged:

func (h *Handler) PayOrder(w http.ResponseWriter,
	r *http.Request) {
	id := r.PathValue("id")
	err := h.svc.Pay(r.Context(), id)
	var pe *PaymentError
	switch {
	case err == nil:
		w.WriteHeader(http.StatusNoContent)
	case errors.Is(err, ErrNotFound):
		http.Error(w, "order not found", http.StatusNotFound)
	case errors.As(err, &pe):
		http.Error(w, pe.Code, http.StatusPaymentRequired)
	default:
		h.log.Error("pay order failed", "id", id, "err", err)
		http.Error(w, "internal error",
			http.StatusInternalServerError)
	}
}

Collecting several errors with errors.Join

Sometimes we want to report all problems together, not only the first one. For example, when we validate an order:

var (
	ErrNoCustomer = errors.New("customer is missing")
	ErrEmptyCart  = errors.New("cart is empty")
)

func (o Order) Validate() error {
	var errs []error
	if o.CustomerID == "" {
		errs = append(errs, ErrNoCustomer)
	}
	if len(o.Items) == 0 {
		errs = append(errs, ErrEmptyCart)
	}
	return errors.Join(errs...) // nil if errs is empty
}
  1. The errors.Join function exists since Go 1.20. It drops nil values. If all of them are nil, it returns nil.
  2. The final error text is the text of all errors, separated by new lines.
  3. The errors.Is and errors.As functions search inside all joined errors. So errors.Is with ErrEmptyCart still returns true.

Handle an error only once

The second bug of the lesson was one error logged three times:

// Bad: log and return at every layer
o, err := s.repo.Find(ctx, id)
if err != nil {
	log.Printf("find failed: %v", err)
	return err
}
  1. Every layer that logs and then returns the error makes one more duplicate line.
  2. The logs get noisy, and alerts are counted several times.
  3. None of the lines has all the context together.

The simple rule: either return the error (with or without more context), or handle it. Never both. Handling means one decision: log it and return an HTTP code, retry, use a fallback value, or ignore it on purpose. Usually the top layer, like the handler or the main loop of a worker, is the place to handle it.

You got an errorIs it a bug that must never happen?Yes: panicCan this layer decide what to do?Yes: handle itlog, HTTP code, retryDo you have useful context?Yes: wrap with %wNo: return itnonoEach error is returned or handled, never both.
Make one decision for each error. If it is a programmer bug, panic. If you can decide right here, handle it. If not, wrap it with context or return it as it is.
Ignoring an error is a decision too If you ignore an error on purpose, assign it to the blank identifier _ and write a comment that says why. An error that is lost silently is the hardest bug to find.

The typed nil trap

This is the fourth bug of the lesson, and a popular interview question:

// Bad: the result is never a nil error
func charge(amount int) error {
	var pe *PaymentError
	if amount <= 0 {
		pe = &PaymentError{Code: "bad_amount"}
	}
	return pe
}

An interface value has two slots: a type and a value. The interface equals nil only when both slots are empty.

  1. When amount is positive, the variable pe is a nil pointer to PaymentError.
  2. On return, this pointer is put into the error interface. The type slot is now “pointer to PaymentError”.
  3. So err != nil is always true, even when the payment worked.
Empty interface valueA nil pointer inside an interfacereturn nilreturn perr // perr == niltypevaluenilniltypevalue*PaymentErrornilerr == nil → trueerr == nil → falseAn interface value is nil only when both type and value are empty.
The error interface has a type and a value. A typed nil pointer fills the type slot, so the interface itself is not nil anymore.

The right way is to return the literal nil on the success path. Also declare error variables with the type error, not with a concrete type:

// Good: return the literal nil on success
func charge(amount int) error {
	if amount <= 0 {
		return &PaymentError{Code: "bad_amount"}
	}
	return nil
}

Error or panic

A panic stops normal execution. Deferred functions run, and if nobody recovers, the whole program ends with a stack trace.

  1. For expected errors, always return an error: order not found, card declined, network down.
  2. Panic is for bugs: a state that must never happen, like an index out of range, or a switch that reached an impossible case.
  3. At program start, a panic is fine. For example regexp.MustCompile with a constant pattern, or config without which the program can not work.
  4. A library must not let a panic cross its package boundary. If it uses panic inside, it must turn it into an error.

The recover function in handlers and goroutines

The recover function stops a panic. It has two conditions:

  1. It must be called directly inside a deferred function.
  2. It only catches a panic in the same goroutine. A recover in another goroutine has no effect.

This is a middleware for the HTTP server:

func Recover(log *slog.Logger, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter,
		r *http.Request) {
		defer func() {
			if v := recover(); v != nil {
				log.Error("panic", "value", v,
					"stack", string(debug.Stack()))
				http.Error(w, "internal error",
					http.StatusInternalServerError)
			}
		}()
		next.ServeHTTP(w, r)
	})
}

The net/http package itself also recovers a panic inside a handler. It logs it and closes the connection. So the server does not stop, but the user gets no clean answer. This middleware gives a 500 answer and a structured log.

Now the fifth bug. The order handler starts a goroutine to send the confirmation email. If that goroutine panics, the recover in the middleware does not see it, because it is in another goroutine. The whole process ends. Every goroutine you start, if it can panic, needs its own recover:

func goSafe(log *slog.Logger, fn func()) {
	go func() {
		defer func() {
			if v := recover(); v != nil {
				log.Error("panic in goroutine", "value", v)
			}
		}()
		fn()
	}()
}
What to do after recover? The recover function does not fix the bug. After a panic, some data may be left half done. Recover only at clear boundaries, like one HTTP request or one worker job, and always log the stack trace.

The defer statement and the error from Close

The defer statement schedules a function for the end of the current function. It is great for releasing resources: closing a file, unlocking a mutex, closing database rows.

But it has a common trap. When you write a file, the data may not really be on disk until Close. So the error from Close matters. This code throws it away:

// Bad: the error from Close is lost
f, err := os.Create(path)
if err != nil {
	return err
}
defer f.Close()

To keep it, use a named result and add the Close error to it inside the deferred function:

func writeReceipt(path string, data []byte) (err error) {
	f, err := os.Create(path)
	if err != nil {
		return err
	}
	defer func() {
		err = errors.Join(err, f.Close())
	}()
	_, err = f.Write(data)
	return err
}
  1. The deferred function runs after return, and it can still change the named result err.
  2. The errors.Join function keeps both errors. If both are nil, the result is nil.
  3. For a file that is only read, a simple deferred f.Close is enough.

Common mistakes

Mistake Result The right way
Returning an error without context The log does not say where the error came from. Add context with fmt.Errorf and %w.
Comparing errors with == Stops working after wrapping. The errors.Is function
Checking the type with a type assertion A wrapped error is not found. The errors.As or errors.AsType function
Logging and returning at every layer One error is logged many times. Handle it once, at the top layer.
Returning a nil pointer of a custom error type The error is never nil. Return the literal nil on success.
Using panic for a normal error The whole program stops. Return an error. Panic only for bugs.
Thinking recover also catches other goroutines A panic in a background goroutine stops the whole server. Run each goroutine with its own recover.
Ignoring the Close error when writing Broken data stays on disk silently. A named result and errors.Join in defer
Wrapping inner errors with %w in a public API Callers depend on inner details. Your own error, or %v

Summary in seven lines

  1. An error in Go is a value. Check it right away with if err != nil, and return early.
  2. Add context with fmt.Errorf and %w. Each layer says what it was doing.
  3. Use errors.Is to check an error and errors.As to get its type. Since Go 1.26 there is also errors.AsType.
  4. Make a sentinel error if only “what happened” matters, and a custom error type if data is needed. Both are part of your API.
  5. Either return an error or handle it, never both. Use errors.Join for several errors.
  6. On the success path return the literal nil, not a typed nil pointer.
  7. Panic is only for bugs. Recover works only in defer and only in the same goroutine. Do not throw away the Close error when writing.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.