Struct e interfacce
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.
Cosa imparerai
- 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.
Punti chiave
- nil means success.
- %w wraps an error with more context.
errors.Isfinds an error inside a wrapped one.
Esempio Go eseguibile
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: idEsercitati
Apri l'esempio nel compilatore online, cambia un valore o aggiungi una riga e prova a prevedere l'output prima di eseguirlo. Poi rompi il codice di proposito e leggi il messaggio del compilatore.
Hai finito questa lezione?
Segnala come imparata per tenere traccia dei tuoi progressi.
I tuoi progressi sono salvati in questo browser Accedi per conservarli su ogni dispositivo.
Esercitati con una sfida
Usa ciò che questa lezione spiega per risolvere un problema reale. Ogni sfida gira nel browser, con test immediati e una revisione dell'IA.
- Prima età non valida Valida le età inserite e segnala dove si trova la prima voce errata invece di far crashare il programma. Facile
- Sommare i numeri validi Somma gli elementi che sono numeri interi e ignora tutto il resto, come fa try/except quando gestisce input non valido. Facile