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
Astoma un puntero al tipo destino y lo rellena.- Así llegas a un campo como Line o Field.
Isresponde cuál error;Asresponde cuál tipo.
Palabras clave y builtins usados aquí
anyerrorfuncifintreturnstringstructtypevar
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.
Paso 3 de 4 en Envolver errores; paso 6 de 15 en Errores.