Structs et 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.

  • Intermédiaire
  • 4 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • Returning errors
  • Wrapping with %w
  • errors.Is and errors.As
findUser(id)
findUser(1)"Ada", nil
findUser(7)wrapped ErrNotFound
findUser(-1)*ValidationError

Check 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.

Points clés

  1. nil means success.
  2. %w wraps an error with more context.
  3. errors.Is finds an error inside a wrapped one.

Exemple Go exécutable

Go
Exécuter le code →
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)
		}
	}
}
Obtenir un bouton Run pour cet exemple Résultat de l'exécution
found Ada
missing: find user 7: user not found
bad input: id

S'entraîner

Ouvrez l'exemple dans le compilateur en ligne, modifiez une valeur ou ajoutez une ligne, et devinez la sortie avant de l'exécuter. Cassez ensuite le code exprès et lisez le message du compilateur.

Leçon terminée ?

Marquez-la comme apprise pour suivre votre progression.

S'entraîner avec un défi

Utilisez le contenu de cette leçon pour résoudre un vrai problème. Chaque défi s'exécute dans le navigateur, avec des tests instantanés et une revue par l'IA.

Tous les défis