errors package implements functions to manipulate errors. It provides functionality for creating, wrapping, and inspecting errors.
Creating Errors
Basic Error Creation
Formatted Errors with fmt.Errorf
Error Wrapping
Wrapping with %w
Multiple Error Wrapping (Go 1.20+)
Error Inspection
errors.Is
Check if an error matches a target error.errors.As
Extract a specific error type from an error chain.errors.Unwrap
Unwrap a wrapped error.Custom Error Types
Simple Custom Error
Custom Error with Wrapping
Error with Is Support
Practical Examples
Multi-Error Accumulation
Error Chain Walking
Retry with Error Context
Sentinel Errors
Error with Context Information
Error Handling Patterns
Early Return
Error Decoration
Panic Recovery with Error
Best Practices
- Use error wrapping - Preserve error context with
%w - Create sentinel errors - Define package-level error variables for common errors
- Use errors.Is and errors.As - Don’t compare errors with
==directly - Provide context - Add information about what was being done when the error occurred
- Don’t ignore errors - Always handle or explicitly ignore with
_ = err - Custom error types - Create custom types for errors with additional information
- Error messages - Start with lowercase, no punctuation at end
- Wrap errors once - Don’t wrap the same error multiple times unnecessarily