The Analogy: The Form Handed Back Across the Counter
You submit a form at a counter. The clerk glances at it, hands it back, and clips a note to the top: box 4 is blank. The note is a piece of paper. You can read it, photocopy it, staple it to a covering letter, file it in a drawer, or throw it away. Nothing was set on fire, no alarm sounded, and the queue behind you did not evacuate the building. In Go, an error is that note: an ordinary value, returned alongside the result, with a signature that says so.
Because it is paper, everything you can do with a value you can do with an error. You can keep a pre-printed note in a drawer and hand out the same one every time -- that is a sentinel like io.EOF or your own ErrNotFound, and callers recognise it by identity. You can design your own form with printed boxes -- a struct type with an Error() string method, carrying the field name, the line number and the offending value, so callers can read the parts rather than parse a sentence. You can put an error in a struct field, in a slice, in a map, return it three functions later, or join twenty of them together.
The contrast worth holding onto is with exceptions. A thrown exception is an invisible edge in the control-flow graph: line 12 jumps to a catch three frames up that you cannot see from line 12. Go refuses to have that edge. The cost is real -- if err != nil { return ... } is the most-typed phrase in the language, and it is genuinely repetitive. The benefit is that every failure path is written down, in the signature and at the call site, and code review can see all of them.
Where the analogy stops: error is an interface, so a nil pointer of a concrete error type stored in an error is not a nil error -- the typed-nil trap from the interfaces lesson, and the single most common Go bug involving errors. And a note you never read is silent: _ = doThing() compiles, doThing() alone compiles if it returns only an error assigned to nothing... which is why linters exist, and why "handle it or return it" has to be a habit rather than a rule the compiler enforces.
Syntax or Core Structure
package main
import (
"errors"
"fmt"
"strconv"
)
// Sentinel: one package-level value, compared with errors.Is.
var ErrNotFound = errors.New("not found")
// Custom type: carries structured data, matched with errors.As.
type RangeError struct {
Field string
Value int
Max int
}
func (e *RangeError) Error() string {
return fmt.Sprintf("%s: %d exceeds max %d", e.Field, e.Value, e.Max)
}
var stock = map[string]int{"bolt": 40, "nut": 7}
func lookup(name string) (int, error) {
n, ok := stock[name]
if !ok {
return 0, fmt.Errorf("lookup %q: %w", name, ErrNotFound) // %w wraps
}
return n, nil
}
func order(name, qty string) (int, error) {
have, err := lookup(name)
if err != nil {
return 0, err // the message is already complete; add nothing
}
n, err := strconv.Atoi(qty)
if err != nil {
return 0, fmt.Errorf("order %s: bad quantity %q", name, qty)
}
if n > have {
return 0, &RangeError{Field: name, Value: n, Max: have}
}
return n, nil
}
func main() {
for _, in := range [][2]string{
{"bolt", "10"},
{"nut", "9"},
{"washer", "1"},
{"bolt", "many"},
} {
n, err := order(in[0], in[1])
if err == nil {
fmt.Printf("ok %s x%d\n", in[0], n)
continue
}
var re *RangeError
switch {
case errors.Is(err, ErrNotFound): // identity, through wrapping
fmt.Printf("missing %v\n", err)
case errors.As(err, &re): // recover the concrete type
fmt.Printf("range %s: asked %d, have %d\n", re.Field, re.Value, re.Max)
default:
fmt.Printf("failed %v\n", err)
}
}
}
Output:
ok bolt x10
range nut: asked 9, have 7
missing lookup "washer": not found
failed order bolt: bad quantity "many"
Three distinct mechanisms are on show. errors.Is asks "is this that particular error?" and sees through %w wrapping. errors.As asks "is there a *RangeError anywhere in this chain, and if so give it to me", which is how a caller reads re.Max instead of scraping a string. And the default branch handles the error nobody classified -- which is most of them, most of the time, and is perfectly fine.
Technical Depth: The Whole Interface Is One Method
The definition
type error interface {
Error() string
}
That is the entire type. Anything with an Error() string method is an error -- no base class, no registration, no throws clause. The zero value of an error variable is nil, which is exactly the value that means "nothing went wrong", so the common case needs no ceremony.
Four ways to produce one
| Way | Looks like | Use when |
|---|---|---|
errors.New | var ErrClosed = errors.New("closed") | A fixed condition callers will test for. Declare it once, at package level. |
fmt.Errorf | fmt.Errorf("read %s: %w", name, err) | Adding context to an error you received. %w keeps the original testable. |
| A struct type | type RangeError struct{ ... } | Callers need the parts: a field name, a line, a status code, a retry hint. |
| A defined string type | type errKind string with func (e errKind) Error() string { return string(e) } | You want comparable, constant errors: const ErrBadInput errKind = "bad input". |
That last one is underused. A const error cannot be reassigned by another package, and it is comparable with ==, which errors.New values are only by pointer identity.
Sentinels, and why == is not enough
errors.New returns a *errorString, so two calls with the same text are different errors. Sentinel matching therefore relies on there being exactly one value:
if err == ErrNotFound { ... } // breaks the moment anyone wraps it
if errors.Is(err, ErrNotFound) { ... } // walks the Unwrap chain
Always write errors.Is. It costs nothing when there is no wrapping and it keeps working when a middle layer adds context later -- which is the change most likely to silently break == in a codebase that has been growing for a year.
Sentinels worth knowing by name
| Sentinel | Meaning |
|---|---|
io.EOF | Input finished normally. Expected, not exceptional. io.ErrUnexpectedEOF is the exceptional one. |
os.ErrNotExist, os.ErrPermission | Test with errors.Is, never by string. os.IsNotExist is the older, wrapping-blind form. |
sql.ErrNoRows | QueryRow found nothing. Usually maps to a 404, not a 500. |
context.Canceled, context.DeadlineExceeded | The caller gave up, or time ran out. Distinguishing them changes what you log. |
strconv.ErrSyntax, strconv.ErrRange | Wrapped inside *strconv.NumError, so errors.As gives you Func, Num and Err. |
errors.As needs a pointer to the target
var re *RangeError
if errors.As(err, &re) { use(re.Max) } // note: &re, a **RangeError
As walks the chain looking for something assignable to *target, so the argument is always the address of the variable you want filled in. Passing re instead of &re panics with errors.As: target must be a non-nil pointer. And because the method set matters, an Error() method on *RangeError means you must search for *RangeError, not RangeError.
Conventions for the message
- Lowercase, no trailing punctuation. Errors get embedded in other errors, and
Failed to open file.: connection refusedreads like a bug because it is one. - No "failed to" / "error while" prefixes. The word "error" is already implied by where it appears.
open config.yaml: permission deniedis the house style. - Sentinels are named
ErrXxx; error types are namedXxxError. - Each layer adds the noun it knows about, and nothing else. Context accumulates left to right into a readable path.
Several errors at once
errors.Join(errs...) (Go 1.20) returns a single error whose message is each non-nil error on its own line, and whose Unwrap() []error exposes them all. errors.Is and errors.As search every branch. It returns nil if every argument is nil, so return errors.Join(problems...) is safe to write unconditionally -- which makes it the natural shape for validators that should report all the problems rather than the first.
Ignoring an error, on purpose
_ = w.Close() says "I have decided this cannot matter", and a reviewer can see the decision. defer f.Close() on a file you only read is that decision, correctly made. defer f.Close() on a file you wrote is a bug: the flush error disappears, and truncated output is exactly the failure you needed to hear about. The errcheck linter (and go vet's narrower checks) find the unintentional cases.
Cost
errors.New and fmt.Errorf both allocate, and fmt.Errorf formats. That is irrelevant on a failure path taken once per request, and it is measurable in a loop that creates thousands of errors it then discards -- validating a million rows, say. If profiling points at error construction, pre-declare sentinels and use errors.Is rather than building a formatted message you throw away.
Real World Example: A Settings Parser That Reports Every Problem
A validator that stops at the first bad line is a bad validator. This one collects a structured error per problem, joins them into one error, and lets the caller decide which classes of problem are fatal.
package main
import (
"errors"
"fmt"
"strconv"
"strings"
)
var (
ErrMalformed = errors.New("malformed line")
ErrUnknownKey = errors.New("unknown key")
)
// Carries the parts a caller might want, and delegates identity to Err.
type FieldError struct {
Line int
Key string
Err error
}
func (e *FieldError) Error() string {
return fmt.Sprintf("line %d: %s: %v", e.Line, e.Key, e.Err)
}
func (e *FieldError) Unwrap() error { return e.Err } // makes errors.Is work
type Settings struct {
Host string
Port int
Verbose bool
}
func parse(text string) (Settings, error) {
var s Settings
var problems []error
for i, raw := range strings.Split(strings.TrimSpace(text), "\n") {
line := i + 1
raw = strings.TrimSpace(raw)
if raw == "" || strings.HasPrefix(raw, "#") {
continue
}
key, val, ok := strings.Cut(raw, "=")
if !ok {
problems = append(problems, &FieldError{line, raw, ErrMalformed})
continue
}
key, val = strings.TrimSpace(key), strings.TrimSpace(val)
switch key {
case "host":
s.Host = val
case "port":
n, err := strconv.Atoi(val)
if err != nil {
problems = append(problems, &FieldError{line, key,
fmt.Errorf("%q is not a number", val)})
continue
}
s.Port = n
case "verbose":
b, err := strconv.ParseBool(val)
if err != nil {
problems = append(problems, &FieldError{line, key,
fmt.Errorf("%q is not a boolean", val)})
continue
}
s.Verbose = b
default:
problems = append(problems, &FieldError{line, key, ErrUnknownKey})
}
}
// Join returns nil when every element is nil, so this is unconditional.
return s, errors.Join(problems...)
}
func main() {
const text = `
# service settings
host = api.internal
port = 8080
verbose = yes
timeout = 30
justnoise
`
s, err := parse(text)
fmt.Printf("settings: host=%s port=%d verbose=%t\n", s.Host, s.Port, s.Verbose)
if err == nil {
fmt.Println("no problems")
return
}
fmt.Println("--- problems ---")
fmt.Println(err) // Join's message: one error per line
// Join's result exposes its members through Unwrap() []error.
joined, ok := err.(interface{ Unwrap() []error })
if !ok {
return
}
fmt.Println("--- classified ---")
for _, e := range joined.Unwrap() {
var fe *FieldError
if !errors.As(e, &fe) {
fmt.Println("other:", e)
continue
}
switch {
case errors.Is(e, ErrUnknownKey):
fmt.Printf("ignorable line %d key %q\n", fe.Line, fe.Key)
case errors.Is(e, ErrMalformed):
fmt.Printf("malformed line %d\n", fe.Line)
default:
fmt.Printf("bad value line %d key %q\n", fe.Line, fe.Key)
}
}
}
Output:
settings: host=api.internal port=8080 verbose=false
--- problems ---
line 4: verbose: "yes" is not a boolean
line 5: timeout: unknown key
line 6: justnoise: malformed line
--- classified ---
bad value line 4 key "verbose"
ignorable line 5 key "timeout"
malformed line 6
*The function returns a value and an error, and both are useful.* parse hands back the Settings it managed to build alongside the problems it found, so host and port are populated even though three lines failed. Returning a zero Settings with the error would have thrown away four-fifths of the work for no reason. The convention "on error, ignore the other return values" is a good default, not a law -- when partial results are meaningful, document that they are and return them.
errors.Join turns a slice of problems into one error without inventing a type. The joined value prints one problem per line, satisfies errors.Is and errors.As across every member, and -- the part that makes the code clean -- returns nil when problems is empty. That means return s, errors.Join(problems...) needs no if len(problems) == 0 guard, and the caller's ordinary if err == nil works unchanged. Before Go 1.20 this required a hand-written MultiError type in every project.
FieldError splits identity from context, and Unwrap is what joins them. ErrUnknownKey is the kind of problem; Line and Key are the circumstances. Because FieldError.Unwrap returns e.Err, one value answers both questions: errors.Is(e, ErrUnknownKey) finds the sentinel three layers down, and errors.As(e, &fe) hands back the struct so fe.Line can be printed. Delete the Unwrap method and the classification collapses -- every problem falls through to bad value, with no compile error to warn you.
The classification loop is the caller's policy, not the parser's. parse has no opinion about whether an unknown key should abort startup; it reports facts. main decides that unknown keys are ignorable, malformed lines are worth naming, and bad values are worth naming with their key. A different caller -- a strict validation command, say -- can make unknown keys fatal without touching the parser. That separation is the practical reason to return structured errors instead of formatted strings: a string can only be printed, but a value can be interrogated.
Common Mistakes
- Returning a nil
*MyErroras anerror. The interface is non-nil, soerr != nilis true with nothing wrong. Declare the return typeerrorand return the literalnil. - Comparing with
==instead oferrors.Is. Works today, silently stops matching the day someone adds%wcontext in a middle layer. - Using
%vwhen you meant%w. The message looks identical and the chain is severed, soerrors.Isanderrors.Asstop finding anything. There is no compiler warning; onlyerrors.Isfailing in a test. - Matching on the message text.
strings.Contains(err.Error(), "not found")breaks when a library rewords its message -- which it is entitled to do at any time. - Passing the target itself to
errors.As.errors.As(err, re)panics; it must be&re. And search for the type whose method set hasError(), which is usually the pointer type. - Forgetting
Unwrapon a custom wrapper type. The struct carries the cause but hides it, soerrors.Iscan never see through it. - Capitalised or punctuated messages.
"Failed to connect."becomes"dial api: Failed to connect.: timeout"once wrapped. Lowercase, no full stop. - Treating
io.EOFas a failure. It is the normal end of input. Onlyio.ErrUnexpectedEOFmeans something broke. - *Logging and returning the same error.* Every layer that does this multiplies the log lines for one incident. Handle it or return it -- not both.
defer f.Close()on something you wrote to.Closeis where the flush error surfaces; discarding it means silently truncated output. Capture it into the named return (the defer lesson's pattern).- Stopping at the first validation error. A user fixing a config file one round-trip per mistake is a bad experience. Collect and
errors.Join.
Best Practices
- Check every error at the point it appears, and either handle it or return it with one noun of context added.
- Declare sentinels once at package level as
ErrXxx, and always test them witherrors.Is. - Use a struct type the moment a caller might want a part of the error rather than the whole sentence.
- Give every custom wrapper an
Unwrap() errormethod, and use%wexactly once perfmt.Errorf. - Keep messages lowercase, unpunctuated, and free of "failed to" -- they are fragments of a path, not sentences.
- Prefer
errors.Joinover a hand-rolled multi-error type, and return it unconditionally. - Make ignoring explicit with
_ =so a reviewer sees a decision rather than an oversight. - Return partial results alongside the error when they are genuinely useful, and say so in the doc comment.
Practice Exercises
- Change
fmt.Errorf("lookup %q: %w", ...)in the first program to use%vinstead of%wand record which line of output changes. Explain whaterrors.Iscan no longer see. - Delete the
Unwrapmethod fromFieldErrorand run the parser again. Report the new--- classified ---block and explain, case by case, why each line moved. - Add a
Kind() stringmethod toFieldErrorreturning"syntax","unknown"or"value", and rewrite the classification loop to use a type assertion for an interface with that method instead oferrors.Is. Say which version survives a new error type better. - Make
parsereturn(Settings, error)where the error is a single*ConfigErrorcontaining[]*FieldError, withUnwrap() []errorimplemented by hand. Confirmerrors.Is(err, ErrUnknownKey)still reports true and explain which method makes that work.