Explain it simply
Explain it simply
When a Go function finishes, it hands back two answers at once: "here is the result" and "did anything go wrong?". If nothing went wrong, the error slot holds nil; otherwise it holds an error value describing the problem. The caller looks at the error before using the result.
In languages with exceptions, an error jumps along a path you cannot see in the code. In Go, every if err != nil line tells the reader directly: "this can fail here, and this is how it is handled".
Problem → Why → Solution
The problem: throwing the error away
On an order form a user mistypes the quantity as "12a". The developer discarded strconv.Atoi's error with _, so qty silently became 0 and an order worth 0 kyat was saved to the database. Elsewhere, code compared error message text, so the logic broke the day a library reworded its message.
qty, _ := strconv.Atoi(input) // "12a" -> qty = 0, error discarded
total := qty * price
saveOrder(total) // saves a 0 kyat order
user, err := findUser(id)
if err != nil && err.Error() == "not found" { // breaks if the text changes
return notFoundPage()
}Why do these bugs happen?
Go returns errors as values but never forces you to handle them; discarding one with _ draws no complaint from the compiler. A failing function also returns a zero value (0 here), so carrying on without checking means working with bad data. Message text is meant for humans; code should identify errors with errors.Is or errors.As.
Core concept: an error is just an interface value
The built-in error type is an interface with a single method, Error() string, so any type with that method can be an error. By convention the error is the last return value and is nil on success. On failure the other results are returned as zero values, and a caller must not trust them while err != nil. Error strings start lowercase and have no trailing punctuation, because they get embedded inside other messages.
When you pass an error up to the next layer, add context: fmt.Errorf("load profile %d: %w", id, err). The %w verb wraps the original error inside the new one, producing a readable chain such as "load profile 42: not found". With %v only the text is copied and the link to the original error is lost.
Callers have two ways to tell errors apart. A sentinel error is a package-level value such as var ErrNotFound = errors.New("not found"), and errors.Is(err, ErrNotFound) searches the whole wrapped chain for it. Once an error is wrapped, err == ErrNotFound is false, so always use errors.Is instead of ==. A typed error is your own struct with an Error() method, used when the error must carry details such as a Field or a Code; errors.As(err, &target) finds that type in the chain and stores it in target.
When several errors can happen together, as in validation, errors.Join(errs...) (available since Go 1.20) combines them into one error, and Is and As check every error inside it. With no errors, errors.Join returns nil. Finally, panic: keep it for programmer bugs such as an index out of range, or for startup problems the program cannot continue past. Expected problems such as a missing file or bad user input are returned as errors.
| Kind | Example | How callers check |
|---|---|---|
| Sentinel error | var ErrNotFound = errors.New(...) | errors.Is(err, ErrNotFound) |
| Typed error | type ValidationError struct{...} | errors.As(err, &verr) |
| Opaque error | fmt.Errorf("read config: %w", err) | Only err != nil |
- The lowest layer creates the error
- Each layer wraps it with %w context
- The caller searches with Is or As
- Log or display it in one place only
%v and == break the chain; %w with errors.Is and errors.As keep it intact.
General pattern
var ErrSomething = errors.New("something failed") // sentinel
func operation(input InputType) (ResultType, error) {
value, err := step(input)
if err != nil {
return zeroValue, fmt.Errorf("operation %v: %w", input, err)
}
return value, nil
}
if errors.Is(err, ErrSomething) { /* handle that case */ }Keep the error as the last result and, as soon as one occurs, return it wrapped together with a zero value (an early return). The success path stays unindented at the left edge.
Example: reporting division by zero as an error
divide() returns an error instead of panicking when b == 0. main() checks err before touching the result, and on failure prints the message and returns early, a shape you will see in Go code everywhere.
package main
import (
"errors"
"fmt"
)
func divide(a int, b int) (int, error) {
if b == 0 {
return 0, errors.New("cannot divide by zero")
}
return a / b, nil
}
func main() {
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Result:", result)
}Code breakdown
- Signature
func divide(a int, b int) (int, error) {Returns two values with the error last. Callers must receive both, so they cannot simply forget it exists.
- Failure
return 0, errors.New("cannot divide by zero")Returns the zero value 0 for the result, and errors.New creates a new error with that message. If callers ever need to recognize this case, promote it to a package-level sentinel such as var ErrDivByZero = errors.New(...).
- Success
return a / b, nilA nil error means "it worked".
- Call
result, err := divide(10, 0)Receives both the result and the error into two variables.
- Check
if err != nil {Checks the error immediately, before using result. Here b is 0, so "Error: cannot divide by zero" is printed and the return means the "Result:" line is never reached.
Error: cannot divide by zeroSentinel errors, %w and errors.Is
findUser() returns the ErrNotFound sentinel, and loadProfile() wraps it with %w plus the ID as context. main() asks errors.Is whether ErrNotFound is anywhere in the chain and treats it like an HTTP 404. The last lines show that Is cannot find it through %v, and that == is false once the error is wrapped.
package main
import (
"errors"
"fmt"
)
var ErrNotFound = errors.New("not found")
var users = map[int]string{1: "Aye", 2: "Ko Ko"}
func findUser(id int) (string, error) {
name, ok := users[id]
if !ok {
return "", ErrNotFound
}
return name, nil
}
func loadProfile(id int) (string, error) {
name, err := findUser(id)
if err != nil {
return "", fmt.Errorf("load profile %d: %w", id, err)
}
return "profile of " + name, nil
}
func main() {
for _, id := range []int{1, 42} {
p, err := loadProfile(id)
if errors.Is(err, ErrNotFound) {
fmt.Println("404:", err)
continue
}
fmt.Println("200:", p)
}
lost := fmt.Errorf("load profile 42: %v", ErrNotFound) // %v, not %w
fmt.Println("Is through %v:", errors.Is(lost, ErrNotFound))
wrapped := fmt.Errorf("load profile 42: %w", ErrNotFound)
fmt.Println("== after wrapping:", wrapped == ErrNotFound)
}The output is "200: profile of Aye", "404: load profile 42: not found", "Is through %v: false" and "== after wrapping: false".
Typed errors and errors.As
ValidationError carries data about which field was wrong. register() wraps it, but errors.As(err, &verr) finds the *ValidationError in the chain and stores it in verr, so verr.Field is readable. The second argument to As must be a pointer to the target variable (&verr).
package main
import (
"errors"
"fmt"
)
type ValidationError struct {
Field string
Reason string
}
func (e *ValidationError) Error() string {
return e.Field + ": " + e.Reason
}
func checkEmail(email string) error {
if email == "" {
return &ValidationError{Field: "email", Reason: "is required"}
}
return nil
}
func register(email string) error {
if err := checkEmail(email); err != nil {
return fmt.Errorf("register: %w", err)
}
return nil
}
func main() {
err := register("")
fmt.Println(err) // register: email: is required
var verr *ValidationError
if errors.As(err, &verr) {
fmt.Println("bad field:", verr.Field) // bad field: email
}
}Returning several errors with errors.Join
If form validation stops at the first problem, users fix one field only to be shown the next error, which is frustrating. validate() collects every problem and returns them as one error with errors.Join. Printed, each error appears on its own line, and errors.Is still finds ErrBadAge inside.
package main
import (
"errors"
"fmt"
)
var (
ErrNoName = errors.New("name is empty")
ErrBadAge = errors.New("age out of range")
)
func validate(name string, age int) error {
var errs []error
if name == "" {
errs = append(errs, ErrNoName)
}
if age < 0 || age > 150 {
errs = append(errs, fmt.Errorf("%w: %d", ErrBadAge, age))
}
return errors.Join(errs...) // nil when errs is empty
}
func main() {
err := validate("", 200)
fmt.Println(err)
fmt.Println("has ErrBadAge:", errors.Is(err, ErrBadAge))
fmt.Println("valid input:", validate("Aye", 30) == nil)
}The output is "name is empty", "age out of range: 200", "has ErrBadAge: true" and "valid input: true".
In real projects
Where this shows up in real projects
The standard library uses these patterns itself. io.EOF is a sentinel meaning "end of file", and sql.ErrNoRows reports that no row matched. A failed os.Open returns a *fs.PathError, and errors.Is(err, fs.ErrNotExist) tells you the file is missing. strconv.Atoi returns a *strconv.NumError that wraps strconv.ErrSyntax.
In a web service, the repository layer turns sql.ErrNoRows into its own ErrNotFound, and the service layer adds context with %w. The HTTP handler then picks the status code in one place, 404 for errors.Is(err, ErrNotFound), 400 when errors.As finds a ValidationError and 500 otherwise, and logs the error there exactly once. The log gets a single line that traces the path, such as "handle order 7: load user 3: query users: connection refused", and database details never leak to the user.
Common mistakes
Common mistakes
1. Discarding the error with _
n, _ := strconv.Atoi(s) yields 0 for bad input and says nothing. At a minimum, return the error to the caller, or handle it right there and leave a comment explaining why ignoring it is safe. Linters such as errcheck can find unchecked errors for you.
2. Comparing errors with == or by message text
As soon as any layer wraps the error with %w, err == ErrNotFound becomes false, and err.Error() == "not found" breaks whenever the wording changes. Use errors.Is(err, ErrNotFound) or errors.As.
3. Using %v where you meant %w
fmt.Errorf("save: %v", err) prints a perfectly good message but cuts the chain, so every errors.Is or errors.As above it returns false. Use %w whenever callers might need to inspect the cause. At an API boundary where you deliberately hide internal details, %v is a valid, conscious choice.
4. Passing errors.As a target that is not a pointer to a variable
Writing var verr *ValidationError; errors.As(err, verr) without the & leaves As nowhere to store its result, so it panics at runtime (go vet warns about it too). Pass the variable's address: errors.As(err, &verr).
Best practices
Best practices
- Either handle an error (log it) or return it, not both; doing both prints the same failure several times.
- Keep wrap context short and descriptive, like "load user 3", without words like "failed to".
- Export sentinels or error types only for cases callers must distinguish, because they become part of your package's public API.
Mini challenge
Mini challenge: parse an age and classify the error
Write parseAge(), which turns a string into an age. Report its three failure kinds as a sentinel error, a typed error and a wrapped strconv error, and tell them apart in main() with errors.Is and errors.As.
- Non-numeric input wraps strconv.Atoi's error with %w
- Values outside 0-130 return a wrapped *RangeError{Value, Min, Max}
- Values under 18 return the ErrTooYoung sentinel, wrapped
- main() tries "25", "abc", "15" and "200" and prints a different message for each case
package main
import (
"errors"
"fmt"
"strconv"
)
// TODO: sentinel ErrTooYoung
type RangeError struct {
// TODO: Value, Min, Max int
}
// TODO: func (e *RangeError) Error() string — "200 is outside 0-130"
func parseAge(s string) (int, error) {
// TODO: strconv.Atoi, then the range check, then the age-18 check;
// wrap every error with %w and some context
return 0, nil
}
func main() {
for _, in := range []string{"25", "abc", "15", "200"} {
// TODO: classify with errors.Is(err, ErrTooYoung), errors.As(err, &rerr)
// and errors.Is(err, strconv.ErrSyntax)
fmt.Println("todo:", in)
}
}
var _, _ = errors.New, strconv.Atoi // keeps the imports used until you need themExpected: The program prints: ok: 25 not a number: parse age "abc": strconv.Atoi: parsing "abc": invalid syntax rejected: parse age 15: too young out of range, max is 130 -> parse age: 200 is outside 0-130
Show hint
Order the checks carefully: put the range check before the under-18 check so a value like -5 becomes a range error rather than "too young". In main(), a switch { case err == nil: ... case errors.Is(...): ... } reads well. strconv.Atoi's error wraps strconv.ErrSyntax, so errors.Is can detect it.
Show solution
package main
import (
"errors"
"fmt"
"strconv"
)
var ErrTooYoung = errors.New("too young")
type RangeError struct {
Value int
Min, Max int
}
func (e *RangeError) Error() string {
return fmt.Sprintf("%d is outside %d-%d", e.Value, e.Min, e.Max)
}
func parseAge(s string) (int, error) {
n, err := strconv.Atoi(s)
if err != nil {
return 0, fmt.Errorf("parse age %q: %w", s, err)
}
if n < 0 || n > 130 {
return 0, fmt.Errorf("parse age: %w", &RangeError{Value: n, Min: 0, Max: 130})
}
if n < 18 {
return 0, fmt.Errorf("parse age %d: %w", n, ErrTooYoung)
}
return n, nil
}
func main() {
for _, in := range []string{"25", "abc", "15", "200"} {
age, err := parseAge(in)
var rerr *RangeError
switch {
case err == nil:
fmt.Println("ok:", age)
case errors.Is(err, ErrTooYoung):
fmt.Println("rejected:", err)
case errors.As(err, &rerr):
fmt.Println("out of range, max is", rerr.Max, "->", err)
case errors.Is(err, strconv.ErrSyntax):
fmt.Println("not a number:", err)
default:
fmt.Println("unexpected:", err)
}
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- error is an interface with an Error() string method; it is the last return value, and nil means success.
- Check the error right away, before using the result, and never discard it with _.
- fmt.Errorf with %w adds context while keeping the chain; %v cuts it.
- Match sentinels with errors.Is and typed errors with errors.As(err, &target), never with == or message text.
- errors.Join combines several errors, and panic is reserved for programmer bugs.
A Tour of Go — Go