typestar

Envolver con %w en Go

fmt.Errorf con %w agrega contexto y deja alcanzable el original.

var ErrNotFound = errors.New("not found")

func loadTour(slug string) error {
    if slug == "" {
        return fmt.Errorf("load tour: %w", ErrNotFound)
    }
    return nil
}

func handler(slug string) string {
    err := loadTour(slug)
    if err == nil {
        return "loaded"
    }
    wrapped := fmt.Errorf("handler: %w", err)
    return fmt.Sprintf("%v | inner=%v", wrapped, errors.Unwrap(wrapped))
}

Cómo funciona

  1. %w registra el error envuelto; %v solo lo formatea.
  2. Cada capa agrega lo que sabe, no un traceback entero.
  3. errors.Unwrap quita una capa de vuelta.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
17
Caracteres a escribir
361
Tokens
84
Ritmo de tres estrellas
100 tpm

Al ritmo de tres estrellas de 100 tokens por minuto, este intento toma unos 50 segundos.

Escribe este fragmento

Paso 1 de 4 en Envolver errores; paso 4 de 15 en Errores.

← Anterior Siguiente →