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
%wregistra el error envuelto;%vsolo lo formatea.- Cada capa agrega lo que sabe, no un traceback entero.
errors.Unwrapquita una capa de vuelta.
Palabras clave y builtins usados aquí
errorfuncifreturnstringvar
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.
Paso 1 de 4 en Envolver errores; paso 4 de 15 en Errores.