Lesson 29 of 38 · Interfaces & Errors
Go Custom Errors and Error Wrapping with %w
A message like invalid age is enough for a human reading a log. Code that handles an error often needs more: which field was wrong, which line failed, how long to wait before trying again. And as an error travels up through your functions, each one should be able to add context without destroying the original. Custom error types and error wrapping give you both.
Custom error types
Any type with an Error() string method is an error, so a struct can carry as much detail as you like:
type CooldownError struct {
Spell string
Seconds int
}
func (e *CooldownError) Error() string {
return fmt.Sprintf("%s is cooling down (%ds left)", e.Spell, e.Seconds)
}
func Cast(spell string, cooldown int) error {
if cooldown > 0 {
return &CooldownError{Spell: spell, Seconds: cooldown}
}
return nil
}
Cast still returns the plain error interface: callers that only care whether it failed don't need to know your type. Usually the method has a pointer receiver and you return a pointer, &CooldownError{...} — that's also the type you'll ask for later with errors.As.
Wrapping with %w
When a function passes an error up, it should say what it was doing. The %w verb of fmt.Errorf wraps the original error inside a new one:
func Attack(cooldown int) error {
if err := Cast("fireball", cooldown); err != nil {
return fmt.Errorf("attack failed: %w", err)
}
return nil
}
func main() {
fmt.Println(Attack(3))
}
attack failed: fireball is cooling down (3s left)
Each layer prepends its context, so the message reads like a story, while the original error is still inside: the errors form a chain. With %v you'd get the same text, but only the words of the original would survive.
errors.Is: is it in the chain?
errors.Is walks the chain looking for a sentinel error. A plain == only looks at the outermost error:
var ErrNotFound = errors.New("not found")
func main() {
err := fmt.Errorf("load save %q: %w", "slot1", ErrNotFound)
fmt.Println(err)
fmt.Println(err == ErrNotFound, errors.Is(err, ErrNotFound))
}
load save "slot1": not found
false true
errors.As: get your type back
errors.As finds the first error in the chain whose type matches your target variable and stores it there. Pass a pointer to that variable:
err := Attack(3)
var cd *CooldownError
if errors.As(err, &cd) {
fmt.Println("try again in", cd.Seconds, "seconds")
}
try again in 3 seconds
A type assertion such as err.(*CooldownError) would fail here, because the outer error is the wrapper made by fmt.Errorf.
errors.Unwrap and errors.Join
errors.Unwrap(err) returns the next error in the chain, or nil. errors.Is and errors.As call it for you, so you'll rarely need it directly.
errors.Join bundles several errors into one — handy when you validate many things at once. Its message puts each error on its own line, and errors.Is and errors.As check every one of them:
err := errors.Join(errors.New("name is empty"), ErrNotFound)
fmt.Println(err)
fmt.Println(errors.Is(err, ErrNotFound))
name is empty
not found
true
Sentinel or custom type?
Use a sentinel like ErrNotFound when callers only need to know which failure happened. Use a custom type when they need details. Either way, wrap it with %w as it travels up.
Common mistakes
%vinstead of%w: the message looks identical, buterrors.Isanderrors.Ascan no longer find the original.- Forgetting the
&:errors.As(err, cd)panics — the target must be a pointer to your variable. ==or a type assertion on a wrapped error: both only see the outermost error.- Returning a nil pointer as an
error: anerrorholding a nil*CooldownErroris notnilin Go. Writereturn nilfor success. - Repeating context: each function adds only its own context, so the chain doesn't stutter.
Assignment
Write the sign-up checks for the Gopher Isles' guild hall.
- Give
*ValidationError(fieldsFieldandProblem) itsError()method. It returnsinvalid <field>: <problem>, e.g.invalid age: must be between 13 and 120. ValidateUser(name string, age int) error:- an empty name returns
&ValidationError{Field: "name", Problem: "must not be empty"}; - otherwise, an age outside 13–120 returns
&ValidationError{Field: "age", Problem: "must be between 13 and 120"}; - otherwise, it returns
nil.
- an empty name returns
Register(users map[string]int, name string, age int) error:- if
ValidateUserfails, return its error wrapped asfmt.Errorf("register %q: %w", name, err); - if
nameis already a key inusers, returnErrDuplicate, wrapped the same way; - otherwise, store
users[name] = ageand returnnil.
- if
InvalidField(err error) stringreturns theFieldof the*ValidationErroranywhere inerr's chain, or""if there is none (also fornil). Useerrors.As.
users := map[string]int{"ana": 30}
Register(users, "bo", 7) // register "bo": invalid age: must be between 13 and 120
Register(users, "ana", 31) // register "ana": name already taken
Register(users, "cy", 25) // nil, and now users["cy"] == 25
InvalidField(Register(users, "", 20)) // "name"Premium lesson
Unlock the full Learn Go course
- All 38 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Custom errors in other languages
- Raising Custom Exceptions in Python · Python
Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.
Lesson last updated on .