go · level 2 · unit 4 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Make your own to carry the details.
A sentinel error says what went wrong, but not the details. How much money was missing? Which box on the form was empty? An error type can carry those details, because error is an interface: any type with an Error() string method satisfies it.
type ShortError struct { Need int } plus a func (e ShortError) Error() string method makes a ready-to-use error type. You can hand back ShortError{Need: 12} anywhere an error is expected.
To get the details back, declare a box of your type and hand its address to : errors.As(err, &short). If one is found, even wrapped inside, it gives true and fills short in.
package main
import "errors"
import "fmt"
type ShortError struct {
Need int
}
func (e ShortError) Error() string {
return fmt.Sprintf("not enough money, need £%v more", e.Need)
}
func main() {
var err error = ShortError{Need: 12}
err = fmt.Errorf("buying the game: %w", err)
fmt.Println(err)
var short ShortError
if errors.As(err, &short) {
fmt.Println("Save up another", short.Need, "pounds")
}
} Use errors.Is to ask whether it is that exact error, and errors.As to ask for one of your error types.
guess first
Sign-up form trouble. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "errors"
import "fmt"
type FieldError struct {
Field string
}
func (e FieldError) Error() string {
return e.Field + " is missing"
}
func main() {
err := fmt.Errorf("signing up: %w", FieldError{Field: "email"})
var fe FieldError
if errors.As(err, &fe) {
fmt.Println("Please fill in:", fe.Field)
} else {
fmt.Println("Unknown problem")
}
}
your turn
Your turn. Return a late library book.
Choose how many days late the library book is. Then hand errors.As the address of the late box, so it can fill it in.
output
press run to see what happens
fix it
Too many library books, and the program panics. Fix it!
output
press run to see what happens
- The panic happens inside
errors.Ason line 13. Read the panic message: what must the target be? errors.Ashas to fill your box, so it needs the box's address, not a copy of the box.- Change limit to &limit inside errors.As on line 13, then run.
nailed it
your errors carry the details now. :D
- Any type with an
Error() stringmethod satisfieserror. - Fields in your error type carry the details.
errors.As(err, &box)finds your error type and fills the box.
new words in your collection
- error type
- errors.As
This lesson isn’t saved. A free account remembers every lesson you finish.