Level: IntermediateGo Lang

Go Error Wrapping with errors.Is and errors.As

8 min read
Go Error Wrapping featured image: wrap, errors.Is and errors.As cards

Go error wrapping lets you add context to an error without losing the original cause. In this post, you will learn how %w, errors.Is, errors.As and errors.Join work together. Then we will run one program that shows each tool in action.

This lesson builds on Go error handling for beginners and Go interfaces. We also use ideas from Go structs and Go file handling. So it helps to read those first.

What Is Go Error Wrapping?

An error in Go is a value. When a low level function fails, it returns an error. Then the caller often adds a note and passes the error up. Wrapping means that the new error keeps the old one inside it, much like a letter inside an envelope.

Think of a courier who finds a locked door. So he writes a new slip that says the delivery failed. Then he attaches the old slip that says the door was locked. Both messages travel together. In the same way, Go error wrapping keeps the full story from the deep cause to the top message.

You wrap an error with fmt.Errorf and the %w verb. Later, you can look inside the wrapper and ask what the real cause was. That is the whole idea of Go error wrapping.

Why Go Error Wrapping Matters

Plain errors lose information while they travel up. When every layer just returns the error, the final message may say “not found” with no clue where. If every layer creates a new text error, the original cause is gone. Here is what Go error wrapping gives you.

  • Clear messages: each layer adds where and why, such as loadProfile(7).
  • Safe checks: the caller can still test for the original error.
  • Better logs: one line tells the whole story from top to bottom.
  • Cleaner decisions: code can react to a type of failure, not to message text.

However, matching on text is fragile. A small wording change breaks the check. Therefore, Go gives you errors.Is and errors.As to test errors by identity and by type.

How Go Error Wrapping Works

Every wrapped error has a pointer to the error inside it. Because of this pointer, the errors form a chain. Go provides tools to walk that chain, and Go error wrapping depends on them.

Go Error Wrapping diagram showing loadProfile wrapping the findUser error that holds ErrNotFound
loadProfile wraps the error from findUser with the percent w verb. The chain keeps ErrNotFound inside, so errors.Is can still find it from the top.

Wrapping with the %w Verb

A call such as fmt.Errorf("loadProfile(%d): %w", id, err) builds a new error. Its text includes your note and the original message. Also, its chain keeps the original error. When you use %v instead of %w, the text looks the same, but the chain is gone.

Checking Identity with errors.Is

With errors.Is(err, target), Go walks the chain and asks if any link equals the target. It works with sentinel errors, which are fixed values such as ErrNotFound or fs.ErrNotExist. Meanwhile, a plain == check fails once the error is wrapped.

Checking Type with errors.As

With errors.As(err, &target), Go also walks the chain, but it looks for a link of a given type. When it finds one, it sets your variable to that value. As a result, you can read extra fields, such as which input was invalid.

Combining Errors with errors.Join

Sometimes two things fail at once. In that case, errors.Join merges several errors into one. Its text shows each message on its own line, and errors.Is can still match any of them.

Go Error Wrapping: Is vs As vs ==

The three checks look alike, so people often mix them up. The table below shows when to use each one.

CheckQuestion it answersSees through wrapping?Use for
err == targetIs this exactly the same value?NoUnwrapped errors only
errors.IsDoes the chain contain this value?YesSentinel errors like ErrNotFound
errors.AsDoes the chain contain this type?YesCustom error types with fields
errors.UnwrapWhat is the next link?One stepRare, manual walking
Go Error Wrapping diagram showing the results of equals, errors.Is and errors.As on a wrapped error
Three checks on a wrapped error. Equals fails, errors.Is succeeds on the value, and errors.As succeeds on the type and fills a variable.

So in daily code, you will almost always reach for errors.Is and errors.As. Plain equality only works when no one has wrapped the error.

Choosing the Right Verb and Helper

Go error wrapping gives you a few choices when you create an error. The table below shows which one fits each need.

You want toUseChain kept?
Create a new base errorerrors.New(“text”)Not applicable
Add context and keep the causefmt.Errorf with %wYes
Add context and hide the causefmt.Errorf with %vNo
Report several failures togethererrors.Join(a, b)Yes, for each one
Attach rich dataA custom type with Error()Yes, when it wraps

Hiding the cause sounds odd, yet it has a use. Suppose your package calls a database library. If you wrap its error with %w, callers may start to depend on that library. Later, you cannot switch it without breaking them. So for an internal detail, return your own error and use %v for the text. For a stable cause, such as a missing file, use %w.

Giving a Custom Type Its Own Unwrap

A custom error type can also hold another error inside it. In that case, add a method named Unwrap that returns the inner error. After that, errors.Is and errors.As walk through your type as well. This is useful when you want both extra fields and a visible cause.

Go Error Wrapping Hands-On: One Program

Now let’s see everything in one file. We make a sentinel error, a custom error type and two functions that wrap errors.

Step 1: Define and Wrap the Errors

First, ErrNotFound is a sentinel value. Next, ValidationError is a type with a field name and a message. The function findUser returns one of them, and loadProfile wraps whatever it gets.

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

type ValidationError struct {
	Field string
	Msg   string
}

func (e *ValidationError) Error() string { return e.Field + ": " + e.Msg }

func findUser(id int) error {
	if id == 0 {
		return &ValidationError{Field: "id", Msg: "must be positive"}
	}
	return ErrNotFound
}

func loadProfile(id int) error {
	if err := findUser(id); err != nil {
		return fmt.Errorf("loadProfile(%d): %w", id, err)
	}
	return nil
}

Let’s look at the key lines. The method on *ValidationError makes it satisfy the error interface. In loadProfile, the %w verb adds the call name and the argument, but it keeps the cause inside. Finally, the pointer receiver means we compare and extract by pointer type.

Step 2: Check the Errors

Then we run the checks. We start with errors.Is and == on the same wrapped error. After that, we use errors.As on a validation failure, unwrap once, test a standard library error and join two errors.

func main() {
	err := loadProfile(7)
	fmt.Println("error text:", err)
	fmt.Println("is ErrNotFound:", errors.Is(err, ErrNotFound))
	fmt.Println("== compare:", err == ErrNotFound)

	err = loadProfile(0)
	var ve *ValidationError
	if errors.As(err, &ve) {
		fmt.Println("validation field:", ve.Field)
	}
	fmt.Println("unwrap once:", errors.Unwrap(err))

	_, err = os.Open("/no/such/file.txt")
	fmt.Println("is fs.ErrNotExist:", errors.Is(err, fs.ErrNotExist))

	joined := errors.Join(errors.New("db failed"), errors.New("cache failed"))
	fmt.Println("joined:")
	fmt.Println(joined)
	fmt.Println("with the verb v the chain is lost:", errors.Is(fmt.Errorf("x: %v", ErrNotFound), ErrNotFound))
}

Here is the real output from our run.

error text: loadProfile(7): user not found
is ErrNotFound: true
== compare: false
validation field: id
unwrap once: id: must be positive
is fs.ErrNotExist: true
joined:
db failed
cache failed
with the verb v the chain is lost: false

As you can see, the wrapped error prints a helpful message, and errors.Is still finds ErrNotFound. The plain == check says false, because the value on top is the wrapper. Then the type check read the field id. Also, os.Open returned an error that matches fs.ErrNotExist, so you can test file errors without reading text. The last line shows the danger of %v, since the chain is lost. This output sums up Go error wrapping in one screen.

Common Mistakes with Go Error Wrapping

  • Using %v instead of %w: the text looks fine, but the chain is gone. So use %w whenever callers may need the cause.
  • Comparing with ==: the check fails after wrapping. Therefore, use errors.Is.
  • Matching on message text: a small edit breaks the check. Instead, test by value or type.
  • Wrapping at every layer with the same note: logs become long and repeat themselves. So add new facts only.
  • Passing a nil error to errors.As without a pointer: this causes a panic. For that reason, pass a pointer to a variable of the target type.

Best Practices for Go Error Wrapping

  • Add context where you know it, such as the function name or the ID.
  • Keep messages short and lower case, because they join into one long line.
  • Export sentinel errors that callers need to check, since they become part of your API.
  • Use custom types for rich data, such as field names or status codes.
  • Wrap once per layer, and log once at the top.
  • Do not wrap if the cause should stay private, because wrapping exposes it to callers.

Practice Task

To practise Go error wrapping, add a third function called loadDashboard that calls loadProfile and wraps the result. Then print the final message for user 7.

Hint: the message should read loadDashboard: loadProfile(7): user not found. After that, confirm that errors.Is still finds ErrNotFound from the top.

Official Resources

These pages describe the packages and ideas used in this lesson.

Quick Recap

  • Go error wrapping adds context and keeps the original cause.
  • Wrap with fmt.Errorf and the %w verb.
  • Use errors.Is for values and errors.As for types.
  • Plain == fails on wrapped errors.
  • errors.Join merges several errors into one.
  • Using %v hides the cause, so use it only when you want that.

What’s Next?

By now, you can pass errors up the call stack without losing the cause. However, creating complex objects with many settings is another common task. So next, we will build a clean API with the functional options pattern.

Next up: Go functional options pattern explained