Structs und 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.
Das lernst du
- 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.
Das Wichtigste
- nil means success.
- %w wraps an error with more context.
errors.Isfinds an error inside a wrapped one.
Ausführbares Go-Beispiel
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: idÜben
Öffne das Beispiel im Online-Compiler, ändere einen Wert oder füge eine Zeile hinzu und sage die Ausgabe voraus, bevor du es ausführst. Bring den Code danach absichtlich zum Scheitern und lies die Meldung des Compilers.
Lektion fertig?
Markiere sie als gelernt, um deinen Fortschritt zu verfolgen.
Dein Fortschritt ist in diesem Browser gespeichert Melde dich an, um ihn auf jedem Gerät zu behalten.
Mit einer Challenge üben
Nutze den Inhalt dieser Lektion, um ein echtes Problem zu lösen. Jede Challenge läuft im Browser, mit sofortigen Tests und einem KI-Review.
- Erstes ungültiges Alter Validiere eingegebene Altersangaben und melde, wo der erste fehlerhafte Eintrag steht, statt das Programm abstürzen zu lassen. Einfach
- Gültige Zahlen summieren Addiere die Einträge, die ganze Zahlen sind, und überspringe alles andere, so wie try/except mit ungültiger Eingabe umgeht. Einfach