Functions and errors
Errors are ordinary values that callers must decide about.
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.
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
MediumReturn a not-found error
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 inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.