Error Handling

Define Golang error wrapping and checking standards using Go 1.13+ errors package.

51|6|Updated Mar 28, 2019
One-click install
npx skills add https://github.com/Mte90/dotfiles --skill error-handling-mte90
Or copy as Structured Prompt for Agent
Please help me install this Agent Skill.
Skill: Error Handling
Source: https://github.com/Mte90/dotfiles/tree/main/.config/opencode/skills/golang/error-handling
Command: npx skills add https://github.com/Mte90/dotfiles --skill error-handling-mte90

SYSTEM DOCUMENTATION & REQUIREMENTS

💡 This Skill includes references (resource) components.

What problem does it solve?

This Skill establishes best practices for handling errors in Golang, ensuring robust and maintainable code by preventing common pitfalls and promoting clear error propagation.

Core Features & Use Cases

  • Standardized Error Wrapping: Learn to add context to errors using fmt.Errorf with %w.
  • Effective Error Checking: Understand when to use errors.Is for sentinel errors and errors.As for specific error types.
  • Use Case: When a function encounters a file I/O error, this Skill guides you to wrap the original error with context like "failed to read configuration file" and ensure the caller can still check if the underlying error was os.ErrNotExist.

Quick Start

Follow the Golang error handling standards for wrapping and checking errors.

Frequently Asked Questions about Error Handling

High-intent search queries and answers about installing and using this skill.

FAQPage Schema
How do I wrap errors in Golang to add context without losing the original error?

To wrap errors in Golang, use `fmt.Errorf` with the `%w` verb. This adds context like "failed to read file" while preserving the original error, allowing callers to inspect the underlying cause using `errors.Is` or `errors.As`.

When should I use errors.Is versus errors.As for error checking in Go?

Use `errors.Is` when checking for specific sentinel errors like `os.ErrNotExist`. Use `errors.As` when you need to extract or check for a specific custom error type to access its additional fields or methods.

What are the best practices for handling errors in Golang to ensure maintainable code?

Golang error management best practices include treating errors as values, handling them exactly once, using `fmt.Errorf` with `%w` for wrapping, and avoiding anti-patterns like string checking or swallowing errors.

Why does comparing Go errors with string checking cause problems?

String checking errors is an anti-pattern because error messages can change, breaking comparisons. Instead, use the `errors` package with `Is` and `As` to reliably check sentinel errors and custom types.

Do I need Go 1.13 or higher to use the standard errors package for error wrapping?

Yes, you need Go 1.13 or higher. This version introduced the `errors` package functions `Is`, `As`, and `Unwrap`, which are required for proper error wrapping and checking standards.