Go Error Handling: When to Wrap, Match, or Hide a Cause
In this article
In Go, you should wrap an error when you need to add context while preserving the original cause, match a sentinel error when you need to branch on a specific failure, and hide the cause when the underlying error is an implementation detail that callers should not see. This article explains the trade-offs and gives concrete rules for each situation.
Background: How Go Errors Work
Go’s error handling is explicit: functions return an error value, and callers check it. Unlike exceptions, errors are ordinary values, so you can assign them, compare them, and wrap them. The standard library introduced error wrapping in Go 1.13 with fmt.Errorf("%w", err) and the errors.Is and errors.As functions. Before that, you often had to use custom types or string matching, which was brittle.
Three operations matter:
- Wrap: add context with
fmt.Errorf("reading config: %w", err)– the original error remains accessible. - Match: check if an error is a specific sentinel (like
io.EOF) or a specific type usingerrors.Isorerrors.As. - Hide: return a new, generic error without the cause, e.g.,
fmt.Errorf("operation failed")– the caller learns nothing about the underlying reason.
Why Wrapping Exists
Wrapping serves two purposes: adding context and preserving the cause. When a function deep in the call stack fails, the error message alone often doesn’t tell you where it originated. Wrapping adds a breadcrumb trail: "reading config: open /etc/app.conf: no such file or directory". The final message includes the original error text, so logs are more useful.
Wrapping also lets you use errors.Is and errors.As to detect specific errors even after they’ve been wrapped. For example, you can wrap an io.EOF with context, and a caller can still check errors.Is(err, io.EOF) to handle that case specially.
Use wrapping when you want to add information that helps a human debug, but you still want the caller to be able to recognize the underlying error programmatically. This is the most common case in production code.
When to Match a Sentinel Error
Matching is about branching. You match when you need to take different actions based on the specific error. Common sentinel errors include io.EOF, sql.ErrNoRows, and context.Canceled. For example, if a database query returns no rows, you might want to return a 404 instead of a 500. That requires matching sql.ErrNoRows.
Use errors.Is to compare against a sentinel value, and errors.As to extract a specific error type. For example:
if errors.Is(err, sql.ErrNoRows) { return nil, ErrNotFound }Matching is also useful for transient errors. If you have a custom type type TimeoutError struct { … }, you can use errors.As to check for it and decide whether to retry.
Match when the caller needs to make a decision. If the caller only needs to log the error, wrapping is enough. If the caller needs to change behavior (retry, fallback, return a different status code), matching is necessary.
When to Hide the Cause
Hiding the cause is sometimes the right choice, but it’s often overused. You hide when the underlying error is an implementation detail that would confuse or mislead the caller. For example, if you have a repository interface that can be backed by a database or an in-memory store, you don’t want to leak sql.ErrNoRows to a caller that doesn’t know about SQL. Instead, you return a domain-specific error like ErrRecordNotFound.
Hiding is also appropriate when the error contains sensitive information, such as file paths or connection strings, that you don’t want to expose to a user-facing API. In that case, you log the full error internally and return a generic message.
However, hiding the cause makes debugging harder. If you hide too aggressively, you lose the ability to trace the root cause. A good rule: hide only at the boundary of a package or service, where the caller should not depend on the implementation. Inside the package, wrap and propagate.
How to Choose: A Decision Framework
When you write a function that returns an error, ask three questions:
- Will a caller need to branch on this error? If yes, define a sentinel or a custom type and return it (or wrap it). If no, go to the next question.
- Will adding context help a human debug this? If yes, wrap the error with
%w. - Is the error an implementation detail that should not leak? If yes, hide it by returning a new error and log the original.
In practice, most errors should be wrapped. Hiding is for API boundaries, and matching is for control flow. Consider the caller’s perspective: what do they need to do with this error? If they only log it, wrap. If they need to recover, match. If they should not know, hide.
Common Mistakes and Misconceptions
One common mistake is using fmt.Errorf with %v instead of %w. This loses the original error, so errors.Is and errors.As no longer work. Another mistake is comparing errors with == when they might be wrapped. Always use errors.Is.
Another misconception is that wrapping is always better. Wrapping adds layers, and if you wrap the same error multiple times, the message becomes long and repetitive. It’s fine to wrap at each layer, but keep the context concise.
Some developers hide errors because they think it’s cleaner, but this often leads to empty messages like “operation failed” that are useless for debugging. If you hide, always log the original error somewhere.
Costs and Trade-offs
Wrapping has a small performance cost because it allocates a new error string. In hot paths, this might matter, but usually not. The bigger cost is readability: a deeply wrapped error message can be long and hard to parse. However, the benefit of traceability outweighs this in most applications.
Hiding reduces coupling but increases the risk of losing information. Matching adds code paths, which can increase complexity. The key is to be consistent. Establish a convention with your team: wrap by default, hide only at boundaries, and match only when you need to branch.
Alternatives and Related Patterns
Go 1.20 introduced errors.Join for combining multiple errors, which is useful when you need to report several failures at once. For example, in a validation function, you might collect all field errors and join them.
Another pattern is the %+v verb with the github.com/pkg/errors package, which adds stack traces. The standard library doesn’t include stack traces by default, but you can add them with a custom error type. Some teams use this for better debugging.
Finally, consider using a custom error type that implements Unwrap() error to control how wrapping works. This is more advanced but gives you flexibility.
Frequently Asked Questions
When should I use errors.Is vs errors.As?
Use errors.Is when you want to check for a specific sentinel error value, like io.EOF. Use errors.As when you want to find an error of a specific type, like a custom TimeoutError. Both work through wrapping.
Should I always wrap errors with %w?
Not always. If you are at the boundary of a package and you don’t want to expose the underlying error, hide it. Otherwise, wrapping is usually a good default because it preserves the cause.
How do I wrap an error without losing the original message?
Use fmt.Errorf("context: %w", err). The %w verb preserves the original error, and the final message includes both the context and the original error’s text.
Is it okay to compare errors with ==?
Only if you are sure the error is not wrapped. In general, use errors.Is because it handles wrapping automatically.
What is the difference between fmt.Errorf with %v and %w?
%v formats the error as a string but discards the error value, so you can’t use errors.Is or errors.As. %w keeps the error in the chain, allowing those functions to work.