typestar

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

  1. As takes a pointer to the target type and fills it in.
  2. That is how you get at a field like Line or Field.
  3. Is answers which error; As answers which type.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 4 in Wrapping, step 6 of 15 in Errors.

← Previous Next →