typestar

errors.Join in Go

Several failures at once, in one error value.

var (
    ErrEmptyTitle = errors.New("title is empty")
    ErrBadStars   = errors.New("stars out of range")
)

func check(title string, stars int) error {
    var problems error
    if title == "" {
        problems = errors.Join(problems, ErrEmptyTitle)
    }
    if stars < 0 || stars > 3 {
        problems = errors.Join(problems, ErrBadStars)
    }
    return problems
}

func summary() (int, bool) {
    err := check("", 9)
    return len(strings.Split(err.Error(), "\n")), errors.Is(err, ErrBadStars)
}

How it works

  1. Join ignores nils, so it composes with optional checks.
  2. errors.Is matches any of the joined errors.
  3. The message is one failure per line.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
452
Tokens
116
Three-star pace
100 tpm

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

Type this snippet

Step 4 of 4 in Wrapping, step 7 of 15 in Errors.

← Previous Next →