typestar

Errors in Go

Sentinel errors, custom types, and wrapping.

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

type ValidationError struct{ Field string }

func (e *ValidationError) Error() string {
    return fmt.Sprintf("invalid field: %s", e.Field)
}

func find(id int) error {
    if id < 0 {
        return fmt.Errorf("lookup %d: %w", id, ErrNotFound)
    }
    return nil
}

How it works

  1. errors.New makes a comparable sentinel.
  2. A type with an Error() string method is an error.
  3. %w in Errorf wraps for errors.Is.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
287
Tokens
67
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 42 seconds.

Type this snippet

Step 2 of 3 in The error value, step 2 of 15 in Errors.

← Previous Next →