---
name: go-error-handling
description: "Best practices for error handling in Go using the standard error interface and wrapping."
language: go
---

# Go Error Handling

Robust error handling patterns in Go to ensure clear failure reporting and easy debugging.

## Guidelines
- **Errors are values**: Treat errors as normal return values.
- **Check errors immediately**: Don't postpone error checking.
- **Wrap errors with context**: Use `fmt.Errorf("...: %w", err)` to add context while preserving the original error for inspection.
- **Use `errors.Is` and `errors.As`**: Use these functions (Go 1.13+) for checking specific error types or values, especially wrapped ones.
- **Define custom error types**: Use structs for errors that need to carry extra data (e.g., error codes).
- **Handle errors once**: Either log the error and stop, or return it to the caller. Don't do both.
- **Sentinel Errors**: Use `var ErrNotFound = errors.New("not found")` for simple, comparable errors.

## Tools & Libraries
- **errors (standard library)**: The core error handling package.
- **pkg/errors**: Historically popular for stack traces (though mostly superseded by standard library wrapping).
- **golangci-lint (errcheck, wrapcheck)**: To ensure errors are checked and wrapped correctly.

## Trigger Scenarios
- When a function can fail and needs to return an error.
- When handling errors from external APIs or databases.
- When designing a package that needs to expose specific error conditions.
- When debugging "silent failures" where errors might have been ignored.

<!-- synapsis-dsai-managed -->
