Wrap and Check Errors in Go With fmt.Errorf("%w") and errors.Is
Add context to Go errors using fmt.Errorf("%w"), inspect wrapped chains with errors.Is and errors.As, and avoid breaking checks with == or %v. After this, callers can log clear context and still match root causes.
Skip ahead
Already wrapping errors with %w? Jump to Case 2: why %v silently breaks errors.Is or Case 3: extracting typed fields with errors.As.
Returning a bare err up three function layers produces useless production logs like EOF or not found with no clue which user ID or file failed. On the other hand, formatting an error with fmt.Errorf("load user: %v", err) breaks programmatic checks so your HTTP handler stops recognizing ErrNotFound and starts returning 500 Internal Server Error instead of 404 Not Found.
Go solves both with %w error wrapping, errors.Is, and errors.As. Verified on Go 1.27.
Case 1: Adding context while preserving sentinel matching
Wrap an error with %w as it bubbles up so logs show the full call context ("lookup id -1: record not found") while callers can still inspect the root cause cleanly with errors.Is:
package main
import (
"errors"
"fmt"
)
var ErrNotFound = errors.New("record not found")
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
Notice that a direct err == ErrNotFound comparison returns false here because err is the wrapped error—always use errors.Is(err, ErrNotFound) instead of ==.
Case 2: Why %v silently breaks errors.Is
Watch how a single character typo—%v instead of %w—produces the exact same printed string while silently breaking error matching:
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
%v formats the error message into a plain string and discards the unwrap chain. Only %w attaches the original error so errors.Is and errors.As can unwrap it through arbitrarily many layers.
Case 3: Extracting structured details with custom error types and errors.As
When a caller needs structured data—such as which JSON field failed validation so an API can return 400 Bad Request with a field-specific message—define a struct implementing Error() string and extract it with errors.As:
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
Case 4: When to use %w vs. %v intentionally
Use %w whenever callers are allowed to inspect and branch on the underlying error (like os.ErrNotExist, sql.ErrNoRows, or context.DeadlineExceeded). Use %v deliberately at a public library boundary only when you want to hide an internal third-party driver error so callers do not accidentally couple to it.
💡 Tip
Keep Go error strings lowercase with no trailing punctuation ("open config: permission denied", not "Failed to open config.") because callers chain them with prefixes like "startup: %w".
Common mistakes
- Comparing wrapped errors with
err == ErrNotFound: Breaks the moment any intermediate layer wraps the error with context; always useerrors.Is. - Checking errors via
strings.Contains(err.Error(), "not found"): Fragile and breaks if wording changes; useerrors.Isorerrors.As. - Logging and returning the same error at every layer: Produces duplicate log lines for one failure—either log/handle or wrap/return, never both.
⚠ Warning
When calling errors.As(err, &target), always pass a pointer to your error type (var ve *ValidationError; errors.As(err, &ve)). Passing a non-pointer or nil target panics at runtime.
What happens if you skip this
Bare errors leave logs with cryptic messages like EOF, while %v formatting breaks errors.Is and turns clean 404/400 responses into noisy 500 server alerts.
Related course: Go for Beginners.
About
Add context to Go errors using fmt.Errorf("%w"), inspect wrapped chains with errors.Is and errors.As, and avoid breaking checks with == or %v. After this, callers can log clear context and still match root causes.
- Responsible
- Jay P
- Last Update
- 11/27/2026
- Reading Time
- 4 min
Reviews
Sign in to write a reviewComments
Sign in to commentNo comments yet.