Structs e interfaces
Go Error Handling: errors.Is and errors.As
Errors are values in Go. Return them, add context with %w, and check them the right way.
Lo que aprenderás
- Returning errors
- Wrapping with %w
- errors.Is and errors.As
findUser(id)
findUser(1)"Ada", nilfindUser(7)wrapped ErrNotFoundfindUser(-1)*ValidationErrorCheck the error, then continue
Go has no exceptions for ordinary failures. A function that can fail returns an error as its last value, and the caller checks whether it is nil.
ErrNotFound is a fixed error value that callers can compare against. %w wraps it with more context, and errors.Is still finds it inside the wrapped error. ValidationError is an error type with its own data, and errors.As extracts it.
Puntos clave
- nil means success.
- %w wraps an error with more context.
errors.Isfinds an error inside a wrapped one.
Ejemplo ejecutable de Go
main.go
package main
import (
"errors"
"fmt"
)
var ErrNotFound = errors.New("user not found")
type ValidationError struct {
Field string
}
func (e *ValidationError) Error() string {
return "invalid " + e.Field
}
func findUser(id int) (string, error) {
if id <= 0 {
return "", &ValidationError{Field: "id"}
}
if id != 1 {
return "", fmt.Errorf("find user %d: %w", id, ErrNotFound)
}
return "Ada", nil
}
func main() {
for _, id := range []int{1, 7, -1} {
name, err := findUser(id)
var validation *ValidationError
switch {
case err == nil:
fmt.Println("found", name)
case errors.Is(err, ErrNotFound):
fmt.Println("missing:", err)
case errors.As(err, &validation):
fmt.Println("bad input:", validation.Field)
}
}
}
found Ada
missing: find user 7: user not found
bad input: idPractica
Abre el ejemplo en el compilador online, cambia un valor o añade una línea y predice la salida antes de ejecutarlo. Después rompe el código a propósito y lee el mensaje del compilador.
¿Terminaste esta lección?
Márcala como aprendida para seguir tu progreso.
Tu progreso está guardado en este navegador Inicia sesión para conservarlo en todos tus dispositivos.
Practica con un reto
Usa lo que cubre esta lección para resolver un problema real. Cada reto se ejecuta en el navegador, con pruebas al instante y una revisión de IA.
- Primera edad no válida Valida las edades escritas y señala dónde está la primera entrada incorrecta en lugar de dejar que el programa falle. Fácil
- Sumar los números válidos Suma las entradas que sean números enteros y omite todo lo demás, como maneja try/except la entrada incorrecta. Fácil