go-error-handling
Use when Go error handling with error wrapping, sentinel errors, and custom error types. Use when handling errors in Go applications.
от TheBushidoCollective★ 202 звезды на GitHub
Установить go-error-handling в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
Go Error Handling
Master Go's error handling patterns including error wrapping, sentinel errors, custom error types, and the errors package for robust applications.
Basic Error Handling
Creating and returning errors:
package main
import (
"errors"
"fmt"
)
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
func main() {
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Result:", result)
}
Using fmt.Errorf:
func processFile(filename string) error {
if filename == "" {
return fmt.Errorf("filename cannot be empty")
}
// Process file...
return nil
}
Error Wrapping
Wrapping errors with context (Go 1.13+):
import (
"errors"
"fmt"
"os"
)
func readConfig(path string) error {
_, err := os.Open(path)
if err != nil {
return fmt.Errorf("failed to read config: %w", err)
}
return nil
}
func main() {
err := readConfig("config.json")
if err != nil {
fmt.Println(err)
// Output: failed to read config: open config.json: no such file
}
}
Unwrapping errors:
func handleError(err error) {
// Unwrap one level
unwrapped := errors.Unwrap(err)
if unwrapped != nil {
fmt.Println("Unwrapped:", unwrapped)
}
// Check if specific error is in chain
if errors.Is(err, os.ErrNotExist) {
fmt.Println("File does not exist")
}
}
Sentinel Errors
Defining and using sentinel errors:
package main
import (
"errors"
"fmt"
)
var (
ErrNotFound = errors.New("resource not found")
ErrUnauthorized = errors.New("unauthorized access")
ErrInvalidInput = errors.New("invalid input")
)
func getUser(id int) (string, error) {
if id < 0 {
return "", ErrInvalidInput
}
if id == 0 {
return "", ErrNotFound
}
return fmt.Sprintf("user-%d", id), nil
}
func main() {
_, err := getUser(0)
if errors.Is(err, ErrNotFound) {
fmt.Println("User not found")
}
}
Custom Error Types
Implementing error interface:
type ValidationError struct {
Field string
Message string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("validation error on %s: %s", e.Field, e.Message)
}
func validateAge(age int) error {
if age < 0 {
return &ValidationError{
Field: "age",
Message: "must be positive",
}
}
if age > 150 {
return &ValidationError{
Field: "age",
Message: "must be less than 150",
}
}
return nil
}
func main() {
err := validateAge(-5)
if err != nil {
fmt.Println(err)
}
}
Type assertions with errors.As:
func handleValidation(err error) {
var validationErr *ValidationError
if errors.As(err, &validationErr) {
fmt.Printf("Field '%s' failed: %s\n",
validationErr.Field,
validationErr.Message,
)
}
}
Multi-Error Handling
Collecting multiple errors:
type MultiError struct {
Errors []error
}
func (m *MultiError) Error() string {
if len(m.Errors) == 0 {
return "no errors"
}
if len(m.Errors) == 1 {
return m.Errors[0].Error()
}
return fmt.Sprintf("%d errors occurred: %v", len(m.Errors), m.Errors)
}
func (m *MultiError) Add(err error) {
if err != nil {
m.Errors = append(m.Errors, err)
}
}
func validateUser(name, email string, age int) error {
errs := &MultiError{}
if name == "" {
errs.Add(errors.New("name is required"))
}
if email == "" {
errs.Add(errors.New("email is required"))
}
if age < 0 {
errs.Add(errors.New("age must be positive"))
}
if len(errs.Errors) > 0 {
return errs
}
return nil
}
Panic and Recover
When to use panic:
// Panic for unrecoverable errors
func mustConnect(dsn string) *DB {
db, err := connect(dsn)
if err != nil {
panic(fmt.Sprintf("failed to connect to database: %v", err))
}
return db
}
// Recover from panics
func safeExecute(fn func()) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic recovered: %v", r)
}
}()
fn()
return nil
}
Error Handling Patterns
Early return pattern:
func processRequest(id int) error {
user, err := fetchUser(id)
if err != nil {
return fmt.Errorf("fetch user: %w", err)
}
if err := validateUser(user); err != nil {
return fmt.Errorf("validate user: %w", err)
}
if err := saveUser(user); err != nil {
return fmt.Errorf("save user: %w", err)
}
return nil
}
Error variable naming:
// Good: specifi
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
- 01
Bash - 02
Read
FAQ
Что делает скилл go-error-handling?
Use when Go error handling with error wrapping, sentinel errors, and custom error types. Use when handling errors in Go applications.
Как установить скилл go-error-handling?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл go-error-handling запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
AnthropicToolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
access
AnthropicManage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
configure
AnthropicSet up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
access
AnthropicManage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…