Skip to content
Codewilds

Lesson 28 of 38 · Interfaces & Errors

Go Error Handling: error Values and if err != nil

medium20 XP3 min read

Go has no exceptions. A function that can fail says so in its signature by returning an error, and the caller decides — right there, in plain code — what to do about it. Go error handling looks wordy at first, but you always see exactly where things can go wrong and what happens when they do.

The error interface

error is a built-in interface with a single method:

type error interface {
	Error() string
}

Any type with an Error() string method is an error — implicit interfaces at work again. A nil error means "no error".

Creating errors

errors.New creates an error with a fixed message; fmt.Errorf formats one, just like fmt.Sprintf:

err := errors.New("bridge is broken")
fmt.Println(err)
err = fmt.Errorf("level %d is locked", 3)
fmt.Println(err)
bridge is broken
level 3 is locked

Returning (value, error)

By convention the error is the last result. On failure, return the zero value for every other result plus the error. On success, return the value and nil:

func Divide(a, b int) (int, error) {
	if b == 0 {
		return 0, errors.New("division by zero")
	}
	return a / b, nil
}

Check errors immediately

Check err on the very next line and return early. The happy path stays at the left margin, while each failure is handled in a short if block:

n, err := strconv.Atoi("42x")
if err != nil {
	fmt.Println("error:", err)
	return
}
fmt.Println(n * 2)
error: strconv.Atoi: parsing "42x": invalid syntax

strconv.Atoi is a typical standard library function returning (int, error). When err is not nil, treat the other results as meaningless — here n is just 0.

Sentinel errors and errors.Is

When callers need to react to one specific failure, declare it once as a package-level sentinel error. By convention its name starts with Err:

var ErrNotFound = errors.New("not found")

func FindScore(scores map[string]int, name string) (int, error) {
	score, ok := scores[name]
	if !ok {
		return 0, ErrNotFound
	}
	return score, nil
}

func main() {
	_, err := FindScore(map[string]int{"ana": 30}, "bo")
	if errors.Is(err, ErrNotFound) {
		fmt.Println("no such player")
	}
}
no such player

Here errors.Is(err, ErrNotFound) gives the same answer as err == ErrNotFound, but it keeps working when the error has been wrapped with extra context — the topic of the next lesson. Make it a habit.

Writing good error messages

Error messages start with a lowercase letter and have no final punctuation, because they are often chained together: load save: open file: permission denied. Say what failed and include the values that help, as in level 3 is locked.

Errors, not panics

panic is for bugs that should never happen. Bad user input, a missing file or a network timeout are expected failures: return an error and let the caller decide what to do.

Common mistakes

  • Ignoring errors: n, _ := strconv.Atoi(s) silently turns bad input into 0.
  • Using the result before checking err: check first, then use the value.
  • Comparing messages: err.Error() == "not found" breaks as soon as the wording changes. Compare with a sentinel using errors.Is.
  • Capitalised messages with punctuation: "File not found." reads badly once it's chained.
  • Mixed signals: returning a non-nil error on success, or a meaningful-looking value together with an error.

Assignment

The starter declares three sentinel errors: ErrNegativeAge, ErrInvalidAmount and ErrInsufficientFunds.

  1. ParseAge(s string) (int, error) converts text to an age:
    • if strconv.Atoi fails, return 0 and its error unchanged (add "strconv" to the imports);
    • a negative number returns 0, ErrNegativeAge;
    • a number above 150 returns 0 and an error with the message age 151 is too high (with the actual number) — use fmt.Errorf;
    • otherwise, return the age and nil.
  2. Withdraw(balance, amount int) (int, error) returns the new balance:
    • an amount of 0 or less returns 0, ErrInvalidAmount;
    • an amount greater than balance returns 0, ErrInsufficientFunds;
    • otherwise, return balance - amount, nil.
ParseAge("42")    // 42, nil
ParseAge("forty") // 0, strconv.Atoi: parsing "forty": invalid syntax
ParseAge("-5")    // 0, ErrNegativeAge
ParseAge("151")   // 0, age 151 is too high
Withdraw(100, 30) // 70, nil
Withdraw(20, 50)  // 0, ErrInsufficientFunds

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
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Errors and exceptions in other languages

Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.

Lesson last updated on .

Write code ↓
Go+20 XP

Lesson 28 is part of the full course. The first 9 lessons are free.

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
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.