Go Foundations·Clarity, then concurrency

Functions and errors

Errors are ordinary values that callers must decide about.

Beginner 13 min read Lesson 7 of 300 Challenge included
What you will be able to do
  • Return an error as the last value.
  • Wrap errors with fmt.Errorf and %w.
  • Do not log and return the same error at every layer.

In plain English

Go functions can return multiple values, so an error is usually the last return. Handle it explicitly, wrap it with context, or return it. There is no hidden exception path; the signature tells the truth.

load.goGo
package lessons

import (
    "errors"
    "fmt"
)

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

func Find(slug string) (Lesson, error) {
    if slug == "" {
        return Lesson{}, fmt.Errorf("find lesson: %w", ErrNotFound)
    }
    return Lesson{Title: "Go"}, nil
}
Your turn

Return a not-found error

Medium

Write Find(slug) that returns ErrNotFound when slug is empty.

GO · starter
func Find(slug string) (Lesson, error) {
    return Lesson{}, nil
}
Check your understanding before moving on.
Knowledge checkQuestion 1

Which verb wraps an error with fmt.Errorf?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Structs and interfaces
Lesson 7 of 300 · 0% of course