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
Joinignores nils, so it composes with optional checks.errors.Ismatches any of the joined errors.- The message is one failure per line.
Keywords and builtins used here
boolerrorfuncifintlenreturnstringvar
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.
Step 4 of 4 in Wrapping, step 7 of 15 in Errors.