WeCodeAcademy

Go Custom Errors

Anything with an Error() string method is an error. You can wrap errors with %w and inspect them with errors.Is and errors.As.

ExampleGo
package main

import (
  "errors"
  "fmt"
)

var ErrNotFound = errors.New("not found")

type ValidationError struct{ Field string }

func (e *ValidationError) Error() string { return "invalid " + e.Field }

func find(id int) error {
  if id == 0 {
    return &ValidationError{Field: "id"}
  }
  return fmt.Errorf("user %d: %w", id, ErrNotFound)
}

func main() {
  err := find(7)
  fmt.Println(err)
  fmt.Println(errors.Is(err, ErrNotFound))

  err = find(0)
  var ve *ValidationError
  if errors.As(err, &ve) {
    fmt.Println("validation problem with", ve.Field)
  }
}
Output
user 7: not found
true
validation problem with id
Quick check

What does %w do in fmt.Errorf?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.