Errors

Go programs express error state with error values.

The error type is a built-in interface similar to fmt.Stringer:

  1. type error interface {
  2. Error() string
  3. }

(As with fmt.Stringer, the fmt package looks for the error interface when printing values.)

Functions often return an error value, and calling code should handle errors by testing whether the error equals nil.

  1. i, err := strconv.Atoi("42")
  2. if err != nil {
  3. fmt.Printf("couldn't convert number: %v\n", err)
  4. return
  5. }
  6. fmt.Println("Converted integer:", i)

A nil error denotes success; a non-nil error denotes failure.

errors.go

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. type MyError struct {
  7. When time.Time
  8. What string
  9. }
  10. func (e *MyError) Error() string {
  11. return fmt.Sprintf("at %v, %s",
  12. e.When, e.What)
  13. }
  14. func run() error {
  15. return &MyError{
  16. time.Now(),
  17. "it didn't work",
  18. }
  19. }
  20. func main() {
  21. if err := run(); err != nil {
  22. fmt.Println(err)
  23. }
  24. }