Errors are values
Go does not use exceptions for normal failures. Functions return an error as the last value, and the caller checks it.
f, err := os.Open("data.txt")
if err != nil {
fmt.Println("could not open file:", err)
return
}
defer f.Close()Creating errors
import "errors"
var ErrNotFound = errors.New("not found")
func findUser(id int) (string, error) {
if id != 1 {
return "", ErrNotFound
}
return "Asha", nil
}Wrapping errors with context
name, err := findUser(5)
if err != nil {
return fmt.Errorf("loading profile: %w", err)
}The %w verb wraps the original error so you can inspect it later.
Checking errors
if errors.Is(err, ErrNotFound) {
fmt.Println("user does not exist")
}Custom error types
type ValidationError struct {
Field string
}
func (e ValidationError) Error() string {
return "invalid field: " + e.Field
}
var ve ValidationError
if errors.As(err, &ve) {
fmt.Println("problem with", ve.Field)
}panic and recover
panic stops normal execution and is for programming mistakes or impossible states, not for expected errors like a missing file.
defer func() {
if r := recover(); r != nil {
fmt.Println("recovered:", r)
}
}()
panic("something went very wrong")Good practice
- Handle every error or return it. Do not ignore it with
_unless you are sure. - Add context when returning errors.
- Keep error messages lowercase and without punctuation.
Practice
Write a function that reads a number from a string, returning a helpful custom error if it is not valid or is negative.
Practice tasks
Reading is not enough. Try these without copying code, then compare with the lesson.
- Return an error from a function and handle it.
- Wrap an error with fmt.Errorf and %w.
- Write a function that never ignores returned errors.
Common mistakes
- Ignoring errors with _.
- Returning an error and a usable value at the same time.
Quick check
How does Go report errors?
By returning an error value.
What does errors.Is do?
Checks if an error matches a target in the chain.