errors.As in Go
Recovering the concrete error type, to read its fields.
type ValidationError struct {
Field string
Value any
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("%s is invalid: %v", e.Field, e.Value)
}
func validate(stars int) error {
if stars < 0 || stars > 3 {
return fmt.Errorf("validate: %w",
&ValidationError{Field: "stars", Value: stars})
}
return nil
}
func explain(stars int) string {
var invalid *ValidationError
if err := validate(stars); errors.As(err, &invalid) {
return "bad field: " + invalid.Field
}
return "valid"
}
How it works
Astakes a pointer to the target type and fills it in.- That is how you get at a field like Line or Field.
Isanswers which error;Asanswers which type.
Keywords and builtins used here
anyerrorfuncifintreturnstringstructtypevar
The run, in numbers
- Lines
- 24
- Characters to type
- 490
- Tokens
- 116
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 70 seconds.
Step 3 of 4 in Wrapping, step 6 of 15 in Errors.