Логотип Go Error Management

Go Error Management

Спільнота
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.

Огляд

Видавецьv0lka
Репозиторійskills
Назва навичкиgo-error-management
Зірки
28
Форки
1
Файли в пакеті
Лише інструкції
ЛіцензіяMIT
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Усе необхідне — в інструкціях

    Усе потрібне моделі міститься в інструкціях — жодних додаткових файлів для синхронізації.

  • Відкритий вихідний код

    Видавець на GitHub: v0lka. Перед установленням перегляньте вихідні файли навички.

Встановлення

Установіть навичку ШІ Go Error Management у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки на GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до розділу «Плагіни» → «Навички».
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/v0lka/skills/tree/main/development/idiomatic-go/go-error-management
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Додати навичку → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

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
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Go Error Management в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Go Error Management, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для певного постачальника, тому навичка Go Error Management не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож поки навичка не потрібна, токени на її інструкції не витрачаються.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

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

Поширені запитання

Що робить навичка ШІ 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.

Навіщо використовувати Go Error Management у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Go Error Management — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Go Error Management у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/v0lka/skills/tree/main/development/idiomatic-go/go-error-management. TypingMind прочитає файл SKILL.md і встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Go Error Management?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Go Error Management?

Зі скількома забажаєте. У TypingMind ви можете використовувати Go Error Management із будь-якою моделлю, яка підтримує навички, зокрема з GPT, Claude, Gemini, Grok, DeepSeek, Mistral чи Llama. Для цього ви використовуєте власні ключі API.

Чи безкоштовна навичка ШІ Go Error Management?

Так. На GitHub цю навичку публікує v0lka за ліцензією MIT. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це набір інструкцій для повторного використання, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти, які вона може викликати, — код, який десь виконується й повертає результат. Натомість навичка ШІ дає моделі знання й пояснює порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі

Створіть власний робочий простір зі ШІ вже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇