typestar

errors.As en Go

Recuperar el tipo concreto del error, para leer sus campos.

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"
}

Cómo funciona

  1. As toma un puntero al tipo destino y lo rellena.
  2. Así llegas a un campo como Line o Field.
  3. Is responde cuál error; As responde cuál tipo.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
24
Caracteres a escribir
490
Tokens
116
Ritmo de tres estrellas
100 tpm

Al ritmo de tres estrellas de 100 tokens por minuto, este intento toma unos 70 segundos.

Escribe este fragmento

Paso 3 de 4 en Envolver errores; paso 6 de 15 en Errores.

← Anterior Siguiente →