Skip to Content
Skip to content
Go for Beginners: Write Reliable Programs and Small Services
Beginner
Courses
Go for Beginners: Write Reliable Programs and Small Services

Handle Errors Without Hiding Them

Check returned errors explicitly, wrap context with fmt.Errorf("%w", err), and inspect wrapped errors using errors.Is and errors.As. After this, you can trace failures cleanly without swallowing errors.

Course content

Sign in to save your progress.

Course Home

In languages with exceptions, a single missing try/catch lets an error unwind silently through six functions until it crashes far from where the problem started. Go takes the opposite approach: an error is just a regular value returned from a function. You check it immediately, add context if you pass it upward, and match specific failures programmatically without fragile string comparisons.

Skip ahead

If you already wrap errors with fmt.Errorf("...: %w", err) and inspect them with errors.Is and errors.As, continue to "Packages, Exports, and go test."

Experiment 1: Adding context while preserving the original error (%w vs. %v)

Suppose your database layer returns a sentinel error ErrNotFound. As that error bubbles up through your service layer, you want to attach context like which user ID failed—without losing the ability for your HTTP handler to recognize ErrNotFound and return 404 Not Found.

Watch the crucial difference between formatting with %v versus wrapping with %w:

package main

import (
	"errors"
	"fmt"
)

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

func main() {
	broken := fmt.Errorf("load user: %v", ErrNotFound)
	wrapped := fmt.Errorf("load user: %w", ErrNotFound)
	fmt.Println("%v matches ErrNotFound:", errors.Is(broken, ErrNotFound))
	fmt.Println("%w matches ErrNotFound:", errors.Is(wrapped, ErrNotFound))
}
%v matches ErrNotFound: false
%w matches ErrNotFound: true

Both broken.Error() and wrapped.Error() print the exact same text ("load user: not found"). Yet %v only copies the text string and throws away the link to ErrNotFound, whereas %w keeps an unwrap chain so errors.Is can walk through any number of layers and still match ErrNotFound.

Experiment 2: Why err == ErrNotFound breaks as soon as anyone wraps

Even when you wrap properly with %w, a direct comparison err == ErrNotFound returns false because the outer error is the wrapper, not the inner sentinel. Always use errors.Is(err, ErrNotFound) instead of ==:

func findUser(id int) (string, error) {
	if id <= 0 {
		return "", fmt.Errorf("lookup id %d: %w", id, ErrNotFound)
	}
	return "alice", nil
}

func main() {
	_, err := findUser(-1)
	fmt.Println("error:", err)
	fmt.Println("is ErrNotFound:", errors.Is(err, ErrNotFound))
}
error: lookup id -1: record not found
is ErrNotFound: true

Experiment 3: Returning structured failure details with custom error types and errors.As

Sometimes a fixed sentinel like ErrNotFound is not enough—an API handler validating a form needs to know which field failed and why so it can highlight that exact input box in JSON. Any struct with an Error() string method is a valid Go error, and errors.As unwraps the chain to extract it:

type ValidationError struct {
	Field string
	Msg   string
}

func (e *ValidationError) Error() string {
	return fmt.Sprintf("invalid %s: %s", e.Field, e.Msg)
}

func main() {
	err := fmt.Errorf("create order: %w", &ValidationError{Field: "qty", Msg: "must be > 0"})
	var ve *ValidationError
	if errors.As(err, &ve) {
		fmt.Printf("field=%s msg=%s\n", ve.Field, ve.Msg)
	}
}
field=qty msg=must be > 0

Notice the clean separation: errors.Is matches a specific error value (like os.ErrNotExist or sql.ErrNoRows); errors.As extracts a specific error type (like *ValidationError or *http.MaxBytesError) so you can inspect its fields.

Experiment 4: Handle once—do not log and return at every layer

A common anti-pattern in new Go services is logging an error inside the repository, logging it again in the service layer, and logging it a third time in the HTTP handler. That floods production logs with three noisy lines for one single failure. Follow one rule: either handle/log the error, or wrap and return it—never both. Let the top-level HTTP handler or main() log the complete wrapped chain once ("create order: lookup id -1: not found").

Common mistakes

  • Swallowing errors with _: Writing _ = os.WriteFile(...) hides disk-full or permission failures and causes mysterious bugs downstream.
  • Matching errors by substring (strings.Contains(err.Error(), "not found")): Fragile and breaks if wording changes; use errors.Is or errors.As.
  • Using panic for ordinary failures: Reserve panic for impossible programmer bugs or broken startup config—not missing database rows or invalid user input.
  • Capitalizing or ending error messages with periods: Keep messages lowercase with no trailing period ("open config: permission denied") because callers wrap them with prefixes like "startup: %w".

💡 Tip

You can inspect standard-library failures cleanly with errors.Is too—for example errors.Is(err, os.ErrNotExist) for missing files, errors.Is(err, sql.ErrNoRows) for empty SQL lookups, and errors.Is(err, context.DeadlineExceeded) for timeouts.

What happens if you skip this step

Returning bare err without context produces cryptic logs like EOF with no clue which file or API failed; wrapping with %v instead of %w silently breaks errors.Is so your API starts returning 500 Internal Server Error instead of 404 Not Found.

Your repository function returns fmt.Errorf("fetch user %d: %v", id, ErrNotFound). What does errors.Is(err, ErrNotFound) return in the HTTP handler, and what single character change fixes it?

About

Check returned errors explicitly, wrap context with fmt.Errorf("%w", err), and inspect wrapped errors using errors.Is and errors.As. After this, you can trace failures cleanly without swallowing errors.

Duration
5 min
Last update
11/27/2026
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.