Bitpath

Lesson 2 · Unit 06

Errors in depth

Errors with data inside, errors wrapped in context, defer and panic.

13 exercisesabout 3 min

What you practise

  • Your own error type, wrapping with %w, errors.Is and errors.As, defer, panic and 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?

Go
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)

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.

Go
// 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 found

Concept

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.

Go
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))
// true

Concept

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.

Go
func work() {
  fmt.Println("open file")
  defer fmt.Println("close file")
  fmt.Println("read file")
}

work()
// open file
// read file
// close file

9 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.

One email when Bitpath is ready to try. Nothing else. Privacy