go-errors-and-context
Design Go error contracts, context propagation, cancellation, deadline budgets, and retry boundaries. Use when adding failures, wrapping dependency errors, or changing operation lifetime.
- License 许可
- MIT
- 最近更新
- 2026-11-14
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- go-errors-and-context
- description
- Design Go error contracts, context propagation, cancellation, deadline budgets, and retry boundaries. Use when adding failures, wrapping dependency errors, or changing operation lifetime.
03 SKILL.md 正文
Go errors and context
Read Documentation/project-context.md and .cratis/ai/rules/go.md first.
Load the transport skill for gRPC status mapping or HTTP response envelopes.
Workflow
- List failures callers must distinguish. Choose a sentinel for a category, a typed error for structured detail, or an opaque translation for private implementation failures. Document which identities callers can inspect.
- Add operation context with
%wonly when the cause is intended public API. A future dependency swap must preserve exposed error semantics. Avoid both logging and returning the same error; log at the boundary making the decision. - Return a real nil
erroron success, not a typed nil in an interface. Preserve important cleanup errors, usingerrors.Joinif the Go minimum supports it and multiple causes belong in the public contract. - Accept
context.Contextfirst and propagate it to blocking dependencies. Do not store request contexts in clients or replace canceled contexts withBackground. Use context values only for request-scoped metadata. - Assign cancel ownership. Child timeouts cannot extend the parent's deadline; call their cancel functions on every path. Cancellation is not a goroutine join.
- Set a total operation budget before retrying; keep attempts and backoff within it. Cancellation during a wait must terminate it. Retrying append after an ambiguous response needs demonstrated server idempotency, not optimism.
- Define whether transport statuses remain inspectable or are translated. Keep domain rejection distinct from transport failure and partial success.
- Test wrapping,
errors.Is/As, nil success, caller cancellation, deadline expiry, cleanup, and ambiguous writes. Update public docs and parity entries.
Small example: bounded propagation
Illustrative helper. It does not retry and deliberately exposes the callback's error identity; the callback must honor its context.
package operation
import (
"context"
"fmt"
"time"
)
// Run executes call within both the parent's and the supplied time budget.
// Errors returned by call remain inspectable through errors.Is and errors.As.
func Run(ctx context.Context, budget time.Duration,
call func(context.Context) error,
) error {
if budget <= 0 || call == nil {
return fmt.Errorf("positive budget and non-nil call required")
}
ctx, cancel := context.WithTimeout(ctx, budget)
defer cancel()
if err := ctx.Err(); err != nil {
return err
}
if err := call(ctx); err != nil {
return fmt.Errorf("run operation: %w", err)
}
return nil
}
A timeout cannot forcibly interrupt a callback that ignores its context. Do not start an unjoinable goroutine to pretend this helper can enforce termination.
Verification boundary
Run targeted error/deadline tests and the repository gates. Stop for an unresolved retry guarantee or public error contract; do not guess transport semantics or claim a timed-out write definitely failed on the server.
References and attribution
- Errors as values
- Wrapping as API
- Context ownership
- Google best practices: Google, CC-BY-3.0; error-boundary advice paraphrased for Cratis. Workflow and example are original.
04 同仓库更多 Skills
spf13-go
Review Go library APIs, package boundaries, tests, iterators and standard-library choices. Load for broad design or idiom reviews after the repository-owned Go skills.
samber-golang-error-handling
Review Go error creation, wrapping, inspection and logging boundaries. Load when changing caller-visible failures after go-errors-and-context.
samber-golang-context
Design Go context propagation, cancellation, deadlines and request metadata. Load for operation-lifetime changes or context-related leaks after go-errors-and-context.
jetbrains-go-modern-guidelines
Choose version-compatible modern Go syntax and standard-library APIs. Load when modernizing touched Go code after reading go.mod and build constraints.
go-testing
Write and review Go unit, contract, transport, race, fuzz, and deterministic concurrency tests. Use for new behavior, bug fixes, flaky tests, and public API parity evidence.
go-release-modules
Review Go module dependencies, minimum versions, compatibility, semantic labels, release-action tags, and proxy discoverability. Use for release preparation, retractions, and major-version migration planning.