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.

  • Intermediário
  • 4 min de leitura
  • 1 exemplo executável
O que você vai aprender
  • 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.

Pontos-chave

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

Exemplo executável de Go

Go
Executar código →
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)
		}
	}
}
Gerar um botão Run para este exemplo Resultado da execução
found Ada
missing: find user 7: user not found
bad input: id

Pratique

Abra o exemplo no compilador online, mude um valor ou adicione uma linha e tente prever a saída antes de executar. Depois quebre o código de propósito e leia a mensagem do compilador.

Terminou esta lição?

Marque como aprendida para acompanhar seu progresso.

Pratique com um desafio

Use o conteúdo desta lição para resolver um problema real. Cada desafio roda no navegador, com testes instantâneos e uma revisão por IA.

Todos os desafios