Logo di Go Error Management

Go Error Management

Community
v0lka
go-error-management

Guides the agent to avoid common Go error management mistakes when writing or reviewing Go code. Covers panic usage, error wrapping vs transforming, checking error types and values correctly with errors.As/errors.Is, handling errors exactly once, explicitly ignoring errors, and handling defer errors. Use when writing, reviewing, or refactoring Go error handling code, or when working with sentinel errors, custom error types, wrapped errors, or defer cleanup.

Panoramica

Pubblicato dav0lka
Repositoryskills
Nome della skillgo-error-management
Stelle
28
Fork
1
File inclusi
Solo istruzioni
LicenzaMIT
Link
  • Istruzioni in Markdown

    Un file SKILL.md che il modello carica quando serve, consumando token solo quando una richiesta è effettivamente pertinente.

  • Funziona con qualsiasi LLM

    Le skill IA sono in semplice Markdown, non in codice specifico di un fornitore, quindi funzionano con GPT, Claude, Gemini, Grok o un modello locale.

  • Tutto nelle istruzioni

    Tutto ciò che serve al modello è nelle istruzioni: nessun file aggiuntivo da sincronizzare.

  • Open source

    Pubblicata da v0lka su GitHub. Leggi i sorgenti prima di installarla.

Installazione

Installa la skill IA Go Error Management in TypingMind per usarla con qualsiasi LLM, oppure copiala in un altro agente in grado di leggere SKILL.md.

1

Installa in TypingMind

TypingMind installa una skill direttamente dalla sua cartella GitHub: legge SKILL.md, raccoglie i file delle risorse e salva il risultato in locale.

  1. Apri l'app e vai su Plugin → Skill.
  2. Scegli "Installa da GitHub".
  3. Incolla l'URL della cartella della skill riportato qui sotto e conferma.
    https://github.com/v0lka/skills/tree/main/development/idiomatic-go/go-error-management
  4. Attiva la skill in ogni chat in cui vuoi averla a disposizione.
Plugin → Skill → Aggiungi skill → Da URL GitHub, poi incolla l'URL della cartella e premi Continua.
2

Installa in un altro agente

Qualsiasi agente che legge il formato Agent Skills può usare questa skill: copia la cartella della skill nella directory delle skill di quell'agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/v0lka/skills.git /tmp/skills
mkdir -p .claude/skills
cp -r /tmp/skills/development/idiomatic-go/go-error-management .claude/skills/go-error-management
Dopo la copia, riavvia Claude Code per caricare la nuova skill.

Usala in TypingMind

Attiva Go Error Management in qualsiasi chat di TypingMind e al resto pensa il modello. Il nome e la descrizione della skill sono nel prompt di sistema e, non appena arriva una richiesta pertinente, il modello carica da solo le istruzioni complete: non devi mai richiamarla manualmente e non consuma token finché non viene effettivamente usata.

Il modello carica automaticamente Go Error Management non appena riceve una richiesta pertinente.

Funziona con qualsiasi modello IA

Le skill IA sono semplici istruzioni in Markdown, non codice specifico di un fornitore, quindi Go Error Management non è vincolata al modello per cui è stata scritta. Installala una sola volta in TypingMind e usala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modello locale che esegui tu, sempre con le tue chiavi API.

  • Caricata solo quando serve

    Il prompt di sistema contiene solo il nome e la descrizione. Le istruzioni vengono recuperate alla prima richiesta pertinente, quindi una skill inutilizzata non costa nulla.

  • Cambia modello durante la chat

    Poiché la skill è composta da istruzioni e non da codice, continua a funzionare anche se cambi modello: il nuovo modello legge lo stesso file SKILL.md.

Istruzioni della skill

Questo è il contenuto di SKILL.md che il modello carica. Leggilo prima dell'installazione: una skill è un insieme di istruzioni che il tuo modello seguirà.

Go Error Management

Rules and patterns for idiomatic Go error handling based on common mistakes #48-#54.


1. Panicking (#48)

Rule: Reserve panic for truly unrecoverable conditions only. Never use panic as a substitute for returning errors.

Acceptable uses of panic:

  • Programmer errors (invariant violations that indicate a bug)
  • Failure to initialize a mandatory dependency during startup (e.g., regexp.MustCompile for a required regex)

Never panic for:

  • User input validation
  • Network/IO failures
  • Any condition the caller could reasonably handle
go
// GOOD: panic for programmer error (invalid invariant)
func MustCompileSchema(pattern string) *regexp.Regexp {
    re, err := regexp.Compile(pattern)
    if err != nil {
        panic(fmt.Sprintf("invalid regex pattern: %s", err))
    }
    return re
}

// BAD: panicking on a runtime error the caller should handle
func GetUser(id string) User {
    u, err := db.FindUser(id)
    if err != nil {
        panic(err) // DO NOT do this
    }
    return u
}

2. Error Wrapping vs Transforming (#49)

Rule: Choose deliberately between wrapping (%w), transforming (%v), and returning directly based on whether the caller should access the source error.

TechniqueExtra contextSource error availableCreates coupling
return errNoYesNo
fmt.Errorf("...: %w", err)YesYes (unwrappable)Yes
fmt.Errorf("...: %v", err)YesNoNo
Custom error type wrappingYesYesYes

Guidelines:

  • Wrap (%w) when the caller legitimately needs to inspect the source error (e.g., checking for sql.ErrNoRows).
  • Transform (%v) when the source error is an implementation detail the caller should not depend on.
  • Return directly when no additional context is needed and the error is already descriptive.
  • Default to %w within a package. Use %v at API boundaries where you want to hide internals.
go
// Wrapping: caller can inspect the source error
return fmt.Errorf("failed to get transaction %s: %w", id, err)

// Transforming: hides implementation detail
return fmt.Errorf("failed to get transaction %s: %v", id, err)

// Direct return: error is already descriptive enough
return err

3. Checking Error Types with errors.As (#50)

Rule: Never use type assertion or type switch to check error types. Always use errors.As, which unwraps the error chain.

A type switch (switch err.(type)) only matches the outermost error. If the target error type is wrapped inside another error via %w, the match silently fails.

go
// BAD: breaks if transientError is wrapped
switch err := err.(type) {
case transientError:
    // This won't match a wrapped transientError
}

// GOOD: works regardless of wrapping depth
var te transientError
if errors.As(err, &te) {
    // te is populated with the matched error
    http.Error(w, te.Error(), http.StatusServiceUnavailable)
} else {
    http.Error(w, err.Error(), http.StatusBadRequest)
}

Important: The second argument to errors.As must be a pointer to the target type. Passing a non-pointer compiles but panics at runtime.


4. Checking Error Values with errors.Is (#51)

Rule: Never use == to compare errors against sentinel values. Always use errors.Is, which traverses the entire wrapped error chain.

go
// BAD: breaks if sql.ErrNoRows is wrapped
if err == sql.ErrNoRows {
    // ...
}

// GOOD: works through any wrapping depth
if errors.Is(err, sql.ErrNoRows) {
    // ...
}

Design guideline for sentinel errors:

  • Expected errors (caller is meant to check for them) -> sentinel values: var ErrNotFound = errors.New("not found")
  • Unexpected errors (structural/contextual info needed) -> custom error types: type ValidationError struct{ ... }

5. Handle an Error Exactly Once (#52)

Rule: An error must be handled exactly once. Logging an error counts as handling it. Returning an error counts as handling it. Never do both.

go
// BAD: handles the error twice (logs AND returns)
func GetRoute(srcLat, srcLng, dstLat, dstLng float32) (Route, error) {
    err := validateCoordinates(srcLat, srcLng)
    if err != nil {
        log.Println("failed to validate source coordinates")
        return Route{}, err // logged AND returned
    }
    // ...
}

// GOOD: handles the error once (wraps and returns, no log)
func GetRoute(srcLat, srcLng, dstLat, dstLng float32) (Route, error) {
    err := validateCoordinates(srcLat, srcLng)
    if err != nil {
        return Route{}, fmt.Errorf("failed to validate source coords: %w", err)
    }
    // ...
}

Consequences of double-handling:

  • Duplicate/interleaved log lines in concurrent code make debugging harder.
  • Context is split across log and error message, neither is complete.

Pattern: Return errors with added context (%w); let the top-level caller (HTTP handler, main, etc.) log once.


6. Explicitly Ignore Errors (#53)

Rule: When intentionally ignoring an error, assign it to the blank identifier _. Never silently discard by omitting assignment.

go
// BAD: unclear if the developer forgot to handle the error
notify()

// GOOD: explicit that error is intentionally ignored
_ = notify()

// BETTER: explain WHY the error is ignored
// At-most-once delivery; acceptable to miss some notifications on error.
_ = notify()

Do not add comments like // Ignore the error -- that just restates the code. Instead explain the rationale for ignoring.


7. Handling Defer Errors (#54)

Rule: Never silently discard errors from defer calls. At minimum, explicitly ignore them. Prefer logging or propagating.

Option A: Log the defer error

go
defer func() {
    if err := rows.Close(); err != nil {
        log.Printf("failed to close rows: %v", err)
    }
}()

Option B: Propagate using named return parameters

When both the main body and the defer can fail, prioritize the original error:

go
func getBalance(db *sql.DB, clientID string) (balance float32, err error) {
    rows, err := db.Query(query, clientID)
    if err != nil {
        return 0, err
    }
    defer func() {
        closeErr := rows.Close()
        if err != nil {
            // Body already failed; log the close error, keep the original.
            if closeErr != nil {
                log.Printf("failed to close rows: %v", closeErr)
            }
            return
        }
        // Body succeeded; surface the close error.
        err = closeErr
    }()

    if rows.Next() {
        if err := rows.Scan(&balance); err != nil {
            return 0, err
        }
        return balance, nil
    }
    // ...
}

Option C: Explicitly ignore (when truly acceptable)

go
defer func() { _ = rows.Close() }()

Never write bare defer rows.Close() when Close() returns an error -- it silently discards the error with no indication of intent.


Quick Reference

MistakeRule
#48 PanickingOnly for programmer errors or mandatory-dependency init failures
#49 Wrapping%w = caller can unwrap; %v = opaque transform; choose intentionally
#50 Error type checkUse errors.As, never type switch/assertion
#51 Error value checkUse errors.Is, never ==
#52 Double handlingEither log or return, never both; wrap with %w for context
#53 Ignoring errorsAssign to _; comment the rationale, not the action
#54 Defer errorsLog, propagate via named returns, or explicitly ignore -- never bare defer

Domande frequenti

Cosa fa la skill IA Go Error Management?

Guides the agent to avoid common Go error management mistakes when writing or reviewing Go code. Covers panic usage, error wrapping vs transforming, checking error types and values correctly with errors.As/errors.Is, handling errors exactly once, explicitly ignoring errors, and handling defer errors. Use when writing, reviewing, or refactoring Go error handling code, or when working with sentinel errors, custom error types, wrapped errors, or defer cleanup.

Perché usare Go Error Management su TypingMind?

Perché la installi una volta e la usi con qualsiasi modello. Go Error Management è scritta in semplice Markdown anziché in codice specifico di un fornitore, quindi la stessa skill funziona con GPT-5, Claude, Gemini, Grok o un modello locale, e puoi cambiare modello durante la chat senza che la skill smetta di funzionare. TypingMind usa le tue chiavi API, quindi paghi direttamente i fornitori anziché un abbonamento per posto utente, e le tue skill e chat restano nel tuo spazio di archiviazione.

Come installo Go Error Management in TypingMind?

Apri Plugin → Skill → Installa da GitHub in TypingMind e incolla https://github.com/v0lka/skills/tree/main/development/idiomatic-go/go-error-management. TypingMind legge il file SKILL.md e installa la skill, che puoi abilitare per ogni singola chat.

Quali modelli IA possono usare Go Error Management?

Qualsiasi modello che colleghi a TypingMind. Le skill IA sono semplici istruzioni in Markdown anziché codice specifico di un fornitore, quindi GPT, Claude, Gemini, Grok e i modelli locali possono tutti caricare questa skill quando una richiesta corrisponde al suo scopo.

Quanti modelli IA posso usare con Go Error Management?

Quanti ne vuoi. Se un modello supporta le skill, puoi usarlo con Go Error Management: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e molti altri, tutti su TypingMind con le tue chiavi API.

La skill IA Go Error Management è gratuita?

Sì. È pubblicata su GitHub da v0lka con licenza MIT. Paghi solo il tuo fornitore IA per i token che usi.

Cosa sono le skill IA?

Una skill IA è un pacchetto di istruzioni riutilizzabili che insegna a un modello IA come svolgere un'attività specifica. Segue il formato aperto Agent Skills: un file SKILL.md con un nome e una descrizione, più eventuali script, template o file di riferimento di cui il modello potrebbe aver bisogno. Il modello legge le istruzioni solo quando la tua richiesta corrisponde alla skill, quindi una skill installata non comporta costi finché non viene usata.

In cosa si differenziano le skill IA dai plugin o dai server MCP?

Un plugin o un server MCP fornisce a un modello nuovi strumenti da richiamare: codice che viene eseguito da qualche parte e restituisce un risultato. Una skill IA, invece, fornisce al modello conoscenze e procedure: come affrontare un'attività, quali passaggi seguire e quali caratteristiche deve avere un buon output. Le skill sono semplici istruzioni in Markdown, quindi non richiedono server, chiavi API né ambienti di esecuzione e funzionano con qualsiasi modello.

Elenco completo

Crea subito il tuo spazio di lavoro AI

Iscriviti alla nostra newsletter per ricevere aggiornamenti sulle nuove funzionalità e sulle prossime iniziative a premi 👇