Errores en Go
Errores centinela, tipos propios y cómo envolverlos.
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
}
Cómo funciona
errors.Newcrea un centinela comparable.- Un tipo con un método
Error() stringes un error. %wenErrorfenvuelve paraerrors.Is.
Palabras clave y builtins usados aquí
errorfuncifintreturnstringstructtypevar
El intento, en números
- Líneas
- 14
- Caracteres a escribir
- 287
- Tokens
- 67
- Ritmo de tres estrellas
- 95 tpm
Al ritmo de tres estrellas de 95 tokens por minuto, este intento toma unos 42 segundos.
Paso 2 de 3 en El error como valor; paso 2 de 15 en Errores.