Lesson 2 · Unit 06
Errors in depth
Errors with data inside, errors wrapped in context, defer and panic.
What you practise
- Your own error type, wrapping with
%w,errors.Isanderrors.As,defer,panicand when not to
Try a question from this lesson
Pick one
You have returned error values since your first functions. error is an interface: anything with an Error() string method. What prints?
type NotFound struct{ Name string }
func (e NotFound) Error() string {
return e.Name + " not found"
}
func find(name string) error {
return NotFound{Name: name}
}
err := find("tea")
fmt.Println(err)Correct answer
tea not found
Why
NotFound has an Error() string method, so it fits the error interface and find may return it. Printing an error calls that method. Your own error type can carry data, here the name that was missing.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
error is an interface
Go's error type is a small interface built into the language, with one method: Error() string.
errors.New("...") gives you a ready-made value that fits it. Your own struct fits it too, once it has that method, and a struct can carry details: which file, which name, which line.
// built into Go:
// type error interface {
// Error() string
// }
type NotFound struct{ Name string }
func (e NotFound) Error() string {
return e.Name + " not found"
}
var err error = NotFound{Name: "tea"}
fmt.Println(err) // tea not foundConcept
Wrapping an error
An error often needs context on its way up: not just "empty", but what was being done.
fmt.Errorf with the verb %w wraps an error: a new message outside, the original kept inside.
The wrapper is a different value, so == no longer matches. errors.Is looks inside the wrapping.
base := errors.New("empty")
err := fmt.Errorf("cart: %w", base)
fmt.Println(err)
// cart: empty
fmt.Println(err == base)
// false
fmt.Println(errors.Is(err, base))
// trueConcept
defer
defer in front of a call means: not now, but when this function returns.
It runs on every way out of the function, an early return included. That makes it the place for clean-up: write the closing step right next to the opening one and it cannot be forgotten.
Several deferred calls run in reverse order: last deferred, first run.
func work() {
fmt.Println("open file")
defer fmt.Println("close file")
fmt.Println("read file")
}
work()
// open file
// read file
// close file9 more exercises in the app
- 4× type the answer
- 1× true or false
- 1× fill the blanks
- 2× multiple choice
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.