Skills Agentes

Golang Error Handling

Manejo idiomático de errores en Go: creación, wrapping con %w, errors.Is/As, errors.Join, tipos de error personalizados, sentinelas, panic/recover, la regla única de manejo, logging estructurado con slog y samber/oops.

Solicitaread edit write glob grep bash(go:*) bash(golangci-lint:*) bash(git:*) agent
Estrellas
3k

en todo el repo

Actividad
57

0–100, la ruta de este skill

Actualizado
el mes pasado

último commit aquí

Commits
4

últimos 90 días

Contexto
1.8k tok

147 tok en reposo

Paquete
5 archivos

34 KB

Instalar

Funciona con cualquier agente que lea SKILL.md

npx -y skills add samber/cc-skills-golang --skill golang-error-handling --agent claude-code

Se instala solo en este repositorio.

Qué hace

  • Aplica reglas idiomáticas de manejo de errores en Go: creación, wrapping con %w, errors.Is/As/Join
  • Impone la 'single handling rule': un error se registra o se devuelve, nunca ambos
  • Guía el uso de tipos de error personalizados, errores sentinela, panic/recover
  • Recomienda slog para logging estructurado y samber/oops para errores de producción
  • Orquesta hasta 5 sub-agentes paralelos para auditar el manejo de errores en bases de código grandes

Úsalo cuando

  • Al crear, envolver, inspeccionar o registrar errores en código Go
  • Al revisar el manejo de errores en un PR
  • Al auditar el manejo de errores en una base de código existente

No lo uses cuando

    Qué lo activa

    Di cualquiera de estas frases y el agente debería cargar este skill.

    • Revisa el manejo de errores de este PR en Go
    • Audita el manejo de errores en todo el repositorio Go
    • Ayúdame a escribir el wrapping de errores para esta función
    • Configura logging estructurado con slog para errores

    SKILL.md

    En inglés

    Persona: You are a Go reliability engineer. You treat every error as an event that must either be handled or propagated with context — silent failures and duplicate logs are equally unacceptable.

    Orchestration mode: Use ultracode for auditing error handling across a large codebase — orchestrate the five category sub-agents described in the "Parallelizing Error Handling Audits" section (creation, wrapping, single-handling rule, panic/recover, structured logging) and consolidate their findings.

    Modes:

    • Coding mode — writing new error handling code. Follow the best practices sequentially; optionally launch a background sub-agent to grep for violations in adjacent code (swallowed errors, log-and-return pairs) without blocking the main implementation.
    • Review mode — reviewing a PR's error handling changes. Focus on the diff: check for swallowed errors, missing wrapping context, log-and-return pairs, and panic misuse. Sequential.
    • Audit mode — auditing existing error handling across a codebase. Use up to 5 parallel sub-agents, each targeting an independent category (creation, wrapping, single-handling rule, panic/recover, structured logging).

    Community default. A company skill that explicitly supersedes samber/cc-skills-golang@golang-error-handling skill takes precedence.

    Go Error Handling Best Practices

    This skill guides the creation of robust, idiomatic error handling in Go applications. Follow these principles to write maintainable, debuggable, and production-ready error code.

    Best Practices Summary

    1. Returned errors MUST always be checked — NEVER discard with _
    2. Errors MUST be wrapped with context using fmt.Errorf("{context}: %w", err)
    3. Error strings MUST be lowercase, without trailing punctuation
    4. Use %w internally, %v at system boundaries to control error chain exposure
    5. MUST use errors.Is for sentinel matching and errors.As/errors.AsType for typed chain inspection instead of direct comparison or bare type assertions. For Go 1.26+, prefer errors.AsType[T](err) when T implements error; use errors.As(err, &target) for Go <1.26 or for non-error interface targets.
    6. SHOULD use errors.Join (Go 1.20+) to combine independent errors
    7. Errors MUST be either logged OR returned, NEVER both (single handling rule)
    8. Use sentinel errors for expected conditions, custom types for carrying data
    9. NEVER use panic for expected error conditions — reserve for truly unrecoverable states
    10. SHOULD use slog (Go 1.21+) for structured error logging — not fmt.Println or log.Printf
    11. Use samber/oops for production errors needing stack traces, user/tenant context, or structured attributes
    12. Log HTTP requests with structured middleware capturing method, path, status, and duration
    13. Use log levels to indicate error severity
    14. Never expose technical errors to users — translate internal errors to user-friendly messages, log technical details separately
    15. Keep log grouping low-cardinality — at logging/APM boundaries, keep message templates stable and attach IDs, paths, line numbers, and counts as structured attributes. Error values may include useful operational context, but avoid putting high-cardinality data into the stable log message used for grouping.

    Detailed Reference

    • Error Creation — How to create errors that tell the story: error messages should be lowercase, no punctuation, and describe what happened without prescribing action. Covers sentinel errors (one-time preallocation for performance), custom error types (for carrying rich context), and the decision table for which to use when.

    • Error Wrapping and Inspection — Why fmt.Errorf("{context}: %w", err) beats fmt.Errorf("{context}: %v", err) (chains vs concatenation). How to inspect chains with errors.Is, errors.As, and Go 1.26+ errors.AsType for type-safe error handling, and errors.Join for combining independent errors.

    • Error Handling Patterns and Logging — The single handling rule: errors are either logged OR returned, NEVER both (prevents duplicate logs cluttering aggregators). Panic/recover design, samber/oops for production errors, and slog structured logging integration for APM tools.

    Parallelizing Error Handling Audits

    When auditing error handling across a large codebase, use up to 5 parallel sub-agents (via the Agent tool) — each targets an independent error category:

    • Sub-agent 1: Error creation — validate errors.New/fmt.Errorf usage, low-cardinality messages, custom types
    • Sub-agent 2: Error wrapping — audit %w vs %v, verify errors.Is/errors.As patterns
    • Sub-agent 3: Single handling rule — find log-and-return violations, swallowed errors, discarded errors (_)
    • Sub-agent 4: Panic/recover — audit panic usage, verify recovery at goroutine boundaries
    • Sub-agent 5: Structured logging — verify slog usage at error sites, check for PII in error messages

    Cross-References

    • → See samber/cc-skills-golang@golang-samber-oops for full samber/oops API, builder patterns, and logger integration
    • → See samber/cc-skills-golang@golang-observability for structured logging setup, log levels, and request logging middleware
    • → See samber/cc-skills-golang@golang-safety for nil interface trap and nil error comparison pitfalls
    • → See samber/cc-skills-golang@golang-naming for error naming conventions (ErrNotFound, PathError)
    • → See samber/cc-skills-golang@golang-continuous-integration skill for automated AI-driven code review in CI using these guidelines

    References

    Reproducido de samber/cc-skills-golang bajo licencia MIT. Leer esta página en markdown.

    Archivos

    5 archivos en el paquete. Solo se lee SKILL.md al activarse — las referencias se cargan si el skill decide que las necesita.

    Antes de instalar

    Requiere el binario `go` y opcionalmente golangci-lint y git instalados.

    Detalles

    Creador
    samber
    Licencia
    MIT
    Recursos incluidos
    referencias
    Código fuente
    Ver SKILL.md

    Etiquetas

    Más de samber/cc-skills-golang

    Este repo incluye 46 skills. Si instalas uno, normalmente ya tienes los demás.

    Buenas prácticas de linting y configuración de golangci-lint para proyectos Golang: ejecutar linters, configurar .golangci.yml, suprimir avisos con nolint, interpretar salidas y elegir linters.

    Costo de contexto al activarse
    1.8k tok
    Tamaño del paquete
    5 archivos
    Última actualización
    hace 3 días
    herramientas desarrollo

    Orquestador de skills de Golang, siempre activo en cualquier tarea de código, revisión, debug o setup: carga las skills más relevantes de samber/cc-skills-golang, a menudo varias a la vez.

    Costo de contexto al activarse
    3.8k tok
    Tamaño del paquete
    4 archivos
    Última actualización
    hace 20 días
    herramientas desarrollo

    Benchmarking, profiling y medición de rendimiento en Golang: escribir y comparar benchmarks, perfilar con pprof, analizar con benchstat y detectar regresiones en CI.

    Costo de contexto al activarse
    3.3k tok
    Tamaño del paquete
    10 archivos
    Última actualización
    hace 28 días
    testing qa

    Patrones y metodología de optimización de rendimiento en Golang: si hay cuello de botella X, aplica el patrón Y, una vez que profiling o benchmarks ya lo identificaron.

    Costo de contexto al activarse
    2.3k tok
    Tamaño del paquete
    9 archivos
    Última actualización
    el mes pasado
    herramientas desarrollo

    Tests de Golang listos para producción: table-driven, suites y mocks con testify, tests paralelos, fuzzing, fixtures, detección de fugas de goroutines con goleak, snapshot testing, cobertura, tests de integración.

    Costo de contexto al activarse
    4.4k tok
    Tamaño del paquete
    6 archivos
    Última actualización
    el mes pasado
    testing qa

    Depura programas Go de forma sistemática hasta encontrar y corregir la causa raíz: metodología de debugging, errores comunes de Go, pprof, Delve, detección de races y depuración en producción.

    Costo de contexto al activarse
    3.2k tok
    Tamaño del paquete
    12 archivos
    Última actualización
    el mes pasado
    testing qa