CodeGym /행동 /Go SELF /Wrapping errors with %w and the chain of causes

Wrapping errors with %w and the chain of causes

Go SELF
레벨 17, 레슨 0
사용 가능

1. Wrapping in fmt.Errorf

If you are just getting started, it may seem that returning fmt.Errorf("something went wrong") is enough, and life is good. But real code quickly becomes multi-layered: main calls run, which calls parse, which calls strconv.Atoi, and somewhere inside everything crashes. In the end, you see an error, but you do not understand in which exact operation it happened or what the root cause was.

Imagine that an error is a package traveling up a chain of functions. Each function is like a sorting hub. It wants to attach its own sticker: "I was parsing now", "I was loading the config now", "I was validating the input now". That is how context appears. But if you attach the stickers incorrectly, you can lose information about what is inside the box.

In Go 1.13 (and, of course, in Go 1.25), there is a standard mechanism for this: wrapping — wrapping an error so that it remains available "inside" and can be extracted with standard tools. This is done with fmt.Errorf and the special placeholder %w.

%v: context was added, but the cause was hidden in text

When we write:

return fmt.Errorf("parse age: %v", err)

we get a nice string, and for a human that is already useful. But technically this is a new error that merely contains the text of the old error. If later someone wants to reach the cause programmatically, there is nothing "inside" anymore — only a string.

It is important to understand this as a mechanism: formatting with %v does not create an unwrap-able chain of causes. Before %w appeared, the result of fmt.Errorf with %v could not be "unwrap"-ed — errors.Unwrap returns nil, which means the original error is not available as a structure.

Let us look at a tiny example: we will add context and then try to "remove one layer".

package main

import (
	"errors"
	"fmt"
)

func main() {
	base := errors.New("bad input")
	w := fmt.Errorf("parse: %v", base)

	fmt.Println(w)                 // parse: bad input
	fmt.Println(errors.Unwrap(w))  // <nil>
}

The comment about what is happening is simple: "parse: bad input" looks fine, but from the program's point of view this is one flat error, without a link to base. That is why %v is "context for a human", but not "context with the cause preserved".

%w: the same text, but an internal cause appears

Now for the interesting part: %w behaves almost the same externally as %v (the text will look similar), but inside it creates a wrapper that can return the root cause through the Unwrap method.

Formally: if fmt.Errorf contains %w, then the returned error gets Unwrap() error, which returns the original error argument.

Let us look at the same example, but with %w:

package main

import (
	"errors"
	"fmt"
)

func main() {
	base := errors.New("bad input")
	w := fmt.Errorf("parse: %w", base)

	fmt.Println(w)                // parse: bad input
	fmt.Println(errors.Unwrap(w)) // bad input
}

The key idea: we added context ("parse"), but did not lose the cause ("bad input"). That is wrapping.

It is important to think of wrapping as creating a new error that "contains" the old one. It is like a matryoshka doll: the top layer says "parse", inside is the original error. You can open one layer of the doll and see what is inside.

3. The chain of causes and errors.Unwrap

Several wrappers in a row

In a real application, an error rarely passes through just one function. Usually it moves upward through several levels, and each level adds its own context.

Go calls the sequence "error → its cause → cause of the cause → ..." a chain of causes. Repeated "unwrap" (removing one layer) lets you move downward through this chain step by step.

Let us build a chain of three levels:

package main

import (
	"errors"
	"fmt"
)

func main() {
	base := errors.New("bad input")
	w1 := fmt.Errorf("parse: %w", base)
	w2 := fmt.Errorf("run: %w", w1)

	fmt.Println(w2)                // run: parse: bad input
	fmt.Println(errors.Unwrap(w2)) // parse: bad input
}

Notice that errors.Unwrap(w2) removes only one layer. That is expected and correct: unwrap means "open one layer of the matryoshka doll", not "take everything apart down to the core".

To make it easier to keep in mind, you can imagine this diagram:

flowchart TD
    A["base: bad input"] --> B["w1: parse: %w(base)"]
    B --> C["w2: run: %w(w1)"]

How to remove layers manually

In application code, people usually do not want to walk the chain by hand, but understanding the mechanism is very useful: it helps you read other people's errors, log them carefully, and avoid breaking the function contract.

The standard library has the errors.Unwrap(err) function, which returns the result of err.Unwrap(), and if unwrap is not supported, it returns nil.

Let us write a small function that prints the chain of causes line by line. This is useful as a debugging tool (and yes, this is that "printf-debugging", only with respect for structure).

package main

import (
	"errors"
	"fmt"
)

func printChain(err error) {
	for err != nil {
		fmt.Println("-", err)
		err = errors.Unwrap(err)
	}
}

And now let us try:

package main

import (
	"errors"
	"fmt"
)

func main() {
	base := errors.New("bad input")
	err := fmt.Errorf("parse: %w", base)
	err = fmt.Errorf("run: %w", err)

	printChain(err)
	// - run: parse: bad input
	// - parse: bad input
	// - bad input
}

This output sometimes looks like "I found an error and decided to read you the entire family tree back to the great-great-grandfather". But for a developer this is gold: you can see where context was added and what the root cause was.

4. Practice: CLI and good error messages

Application skeleton

Now we will continue our learning path: a simple console application that accepts a command and an argument, validates the input, and performs an action. No structures and no databases — we are still in the beginner league, but the errors will already be "grown-up".

Let the application understand the command add <title>. We read input as two words via fmt.Scan (yes, a title without spaces is a limitation, but it is enough for today's topic).

First, let us make a basic "skeleton" with run():

package main

import (
	"fmt"
)

func run() error {
	var cmd, arg string
	fmt.Scan(&cmd, &arg)
	fmt.Println("cmd =", cmd, "arg =", arg) // cmd = add arg = test
	return nil
}

func main() {
	_ = run()
}

Command validation and wrapping the cause

Now let us add command validation and errors. We want run() to return an error upward, and main() to print it as the final result. This is a good style: "inside" we return errors, "outside" we decide what to show the user.

Let us create a parseCommand function:

package main

import (
	"errors"
	"fmt"
)

var ErrBadInput = errors.New("bad input")

func parseCommand(cmd string) error {
	if cmd != "add" {
		return fmt.Errorf("unknown command %q: %w", cmd, ErrBadInput)
	}
	return nil
}

Pay attention: we return context ("unknown command ...") and wrap ErrBadInput with %w. That means the cause "bad input" is preserved inside.

Let us connect this in run():

package main

import "fmt"

func run() error {
	var cmd, arg string
	fmt.Scan(&cmd, &arg)

	if err := parseCommand(cmd); err != nil {
		return fmt.Errorf("run: %w", err)
	}

	_ = arg
	return nil
}

And finally — main, which prints the error:

package main

import "fmt"

func main() {
	if err := run(); err != nil {
		fmt.Println("ERROR:", err) // ERROR: run: unknown command "list": bad input
	}
}

It looks simple, but inside we already have a chain: run → parseCommand → ErrBadInput.

%w vs %v: a short comparison

When you are starting out, it is very easy to mix them up: "both print an error, so why do we need two?" The difference is not in how pretty the string looks, but in whether we preserve the cause as a structure.

What we do Example What a person sees Can the cause be removed via errors.Unwrap?
Added text, but hid the cause in a string
fmt.Errorf("parse: %v", err)
parse: <err text> No (Unwrap returns nil)
Added text and preserved the cause
fmt.Errorf("parse: %w", err)
Almost the same Yes (Unwrap returns err)

And this is where an important engineering idea appears: the decision to "wrap or not wrap" is a contract decision, not a logging decision. By wrapping, you make the internal cause available to the caller; by not wrapping, you hide details for the sake of abstraction.

How to write good context

Error context is not a place for a novel like "War and Peace: Chapter 1, where I tried to parse a string". Good context is a short answer to the question: what operation were we performing when everything broke.

For example, these contexts usually help:

  • read input
  • parse age
  • validate command
  • save task

And these contexts are almost useless:

  • error
  • something went wrong
  • failed

Let us improve our CLI by adding argument validation. Suppose the task title cannot be empty (for fmt.Scan this is almost never encountered, but it is useful as an example):

package main

import (
	"errors"
	"fmt"
)

var ErrBadInput = errors.New("bad input")

func parseTitle(arg string) (string, error) {
	if arg == "" {
		return "", fmt.Errorf("title: %w", ErrBadInput)
	}
	return arg, nil
}

Now let us add context for each step in run():

package main

import "fmt"

func run() error {
	var cmd, arg string
	fmt.Scan(&cmd, &arg)

	if err := parseCommand(cmd); err != nil {
		return fmt.Errorf("parse command: %w", err)
	}

	title, err := parseTitle(arg)
	if err != nil {
		return fmt.Errorf("parse title: %w", err)
	}

	fmt.Println("added:", title) // added: test
	return nil
}

It becomes wordy, but if something breaks, you can almost always understand where exactly, at which step, and what the cause was.

When %w should not be used

It is very tempting to make a rule: "always use %w." But Go does not make this into dogma on purpose: absolute rules like "always %w" are wrong, because sometimes you do not want to expose the internal cause.

Imagine that inside your application there is a layer that works with some library. If you start returning errors outward in a way that allows them to be unwrap-ed down to specific types/values from that library, you are, in a sense, promising: "this library is part of my public behavior." And then you may want to replace the library — and suddenly you break external code that relied on a specific cause.

For our small CLI, you can feel this like this. Suppose somewhere inside we have a function that "reads the config" (for now it is just a simulation):

package main

import (
	"errors"
	"fmt"
)

func loadConfig() error {
	internal := errors.New("low-level config format error")
	return fmt.Errorf("load config: %v", internal) // do not expose internals
}

Here we intentionally use %v: we explained everything to the human ("load config ..."), but we do not give the "cause as a structure" to the outside world. Such a choice can be useful at module boundaries so that external code does not start depending on your internal details.

5. Typical mistakes when wrapping with %w

Mistake #1: using %v and expecting the cause to remain as a structure.
From the outside the string looks almost the same ("parse: bad input"), so a beginner honestly thinks everything was done correctly. But %v simply inserts text, and errors.Unwrap will not be able to extract the original error. If you want a chain of causes — use %w.

Mistake #2: writing context about "nothing".
Phrases like fmt.Errorf("error: %w", err) add noise but do not add meaning. Context should answer the question "what were we doing": parse title, read input, load config. Then a single message is enough to understand where to look for the problem without opening the entire project.

Mistake #3: duplicating the cause in the context.
Sometimes you end up with something like fmt.Errorf("bad input: %w", ErrBadInput). This looks like "bad input: bad input" — as if the error record got stuck in a loop. Context and cause should complement each other: context is about the operation, cause is about the type of problem.

Mistake #4: wrapping nil and wondering why "there is no error".
In Go, people often write wrapping inside if err != nil { ... }. This is not a ritual for beauty: if you blindly try to wrap an error without checking that it actually exists, you can get strange effects. The habit is simple: first check err != nil, then wrap.

Mistake #5: turning %w into "always and everywhere", breaking abstraction boundaries.
Wrapping makes the cause available to external code. Sometimes that is exactly what you need, but sometimes you expose internal implementation details and accidentally turn them into part of the contract. The decision to "wrap or not wrap" depends on whether you want the caller to be able to inspect the cause.

1
과제
Go SELF, 레벨 17, 레슨 0
잠금
등록 폼 나이
등록 폼 나이
1
과제
Go SELF, 레벨 17, 레슨 0
잠금
두 가지 래핑 모드
두 가지 래핑 모드
1
과제
Go SELF, 레벨 17, 레슨 0
잠금
원인 체인
원인 체인
1
과제
Go SELF, 레벨 17, 레슨 0
잠금
CLI에서의 나눗셈
CLI에서의 나눗셈
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION