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
errors.Newmakes a comparable sentinel.- A type with an
Error() stringmethod is an error. %winErrorfwraps forerrors.Is.
Keywords and builtins used here
errorfuncifintreturnstringstructtypevar
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.
Step 2 of 3 in The error value, step 2 of 15 in Errors.