Understand the contract

Wrapping an error adds operation context while preserving the original cause for inspection. Use fmt.Errorf with %w, then errors.Is to look for a particular sentinel in the resulting chain. This lets callers react to a known failure without depending on the exact wording shown to a human.

A sentinel is a shared error value used to identify a category. The example defines ErrMissing once and wraps it with a user identifier. errors.Is follows wrapping relationships. For a structured error type carrying fields, errors.As can recover a matching typed error instead of inspecting a message.

Work through the example

loadUser returns contextual information while main still recognizes the missing-data condition. The program prints the fallback message. Replacing %w with %v retains readable text but loses this wrapping relationship. Choose %w when revealing the underlying error category is part of your API contract.

package main

import (
    "errors"
    "fmt"
)

var ErrMissing = errors.New("missing")

func loadUser(id int) error {
    return fmt.Errorf("load user %d: %w", id, ErrMissing)
}

func main() {
    err := loadUser(7)
    if errors.Is(err, ErrMissing) { fmt.Println("use a fallback") }
}

Watch this boundary

Comparing err.Error() with a literal breaks when wording changes or context is added. Also, returning a wrapped implementation-specific error can expose a dependency decision to callers. Decide which categories are stable before encouraging consumers to match them across package boundaries.

Practice with a changed input

Add another wrapping layer and confirm errors.Is still recognizes ErrMissing. Then replace the inner sentinel with a different error and verify that the fallback no longer matches.

References & further reading

Need help with your Go backend?

I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.

Explore Go consulting services