This repository provides a comprehensive demonstration of error handling patterns and best practices in Go.
Go has a unique approach to error handling, treating errors as values and encouraging explicit error checks. This project showcases various error handling techniques and patterns that will help you write more robust Go code.
The demo covers the following error handling patterns:
- Basic Error Handling: The fundamental
if err != nilpattern - Creating Errors: Using
errors.Newandfmt.Errorf - Custom Error Types: Creating structured error types with additional context
- Error Wrapping/Unwrapping: Using Go 1.13+ error wrapping capabilities
- Panic and Recovery: Handling exceptional situations with panic/recover
- Context-Based Cancellation: Using the context package for timeouts and cancellation
- Concurrent Error Handling: Managing errors across multiple goroutines
- Sentinel Errors: Using predefined error values for specific error conditions
- Best Practices: Guidelines for effective error handling in Go
- Go 1.13 or later (for error wrapping features)
- Clone this repository
- Navigate to the project directory
- Run the demonstration:
cd error-demo
go run main.goThe program will automatically step through each error handling pattern, showing both the code examples and their actual execution.
Go functions that can fail typically return an error as their last return value. The caller checks if this error is nil to determine if the operation succeeded.
file, err := os.Open("file.txt")
if err != nil {
// Handle the error
return err
}
// Use the fileBy implementing the error interface, you can create custom error types that include additional context:
type ValidationError struct {
Field string
Message string
}
func (e ValidationError) Error() string {
return fmt.Sprintf("validation failed for field '%s': %s", e.Field, e.Message)
}Error wrapping allows you to add context while preserving the original error:
if err := doSomething(); err != nil {
return fmt.Errorf("operation failed: %w", err)
}Some key best practices demonstrated include:
- Always check errors returned by functions
- Add context when wrapping errors
- Use custom error types for domain-specific errors
- Use sentinel errors for expected error conditions
- Make operations cancellable with contexts
- Use panic only for exceptional situations
This project uses GitHub Actions to:
- Automatically build and test the code on every push to the main branch
- Build binaries for multiple platforms when a tag is pushed
- Binaries are built for Linux, macOS, and Windows
.github/workflows/go.yml- Builds and tests the code on push.github/workflows/release.yml- Builds binaries for multiple platforms when a tag is pushed
This project is open source and available for learning and reference purposes.
- The Go community for establishing these error handling patterns
- The Go team for their work on improving error handling in Go 1.13+