Error Handling Patterns
Error Handling Fundamentals
Golang provides multiple strategies for robust error management:
graph TD
A[Error Handling] --> B[Explicit Error Checking]
A --> C[Error Wrapping]
A --> D[Panic and Recover]
A --> E[Custom Error Types]
Basic Error Checking Pattern
func processData(data string) error {
if data == "" {
return fmt.Errorf("invalid data input")
}
return nil
}
func main() {
err := processData("")
if err != nil {
fmt.Println("Error occurred:", err)
os.Exit(1)
}
}
Error Wrapping and Context
func validateConfig(path string) error {
if _, err := os.Stat(path); os.IsNotExist(err) {
return fmt.Errorf("config file not found: %w", err)
}
return nil
}
Error Type Comparison
Pattern |
Use Case |
Complexity |
Simple Error Checking |
Basic error scenarios |
Low |
Error Wrapping |
Adding context to errors |
Medium |
Custom Error Types |
Specialized error handling |
High |
Panic and Recover Pattern
func recoverFromPanic() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
os.Exit(1)
}
}()
// Simulated critical section
panic("unexpected error")
}
Advanced Error Handling
type CustomError struct {
Code int
Message string
}
func (e *CustomError) Error() string {
return fmt.Sprintf("Error %d: %s", e.Code, e.Message)
}
func validateInput(input string) error {
if len(input) == 0 {
return &CustomError{
Code: 100,
Message: "Empty input not allowed",
}
}
return nil
}
Best Practices
- Always handle errors explicitly
- Provide meaningful error messages
- Use error wrapping for additional context
- Avoid silent error suppression
- Log errors for debugging
LabEx recommends developing a consistent error handling strategy that balances simplicity and comprehensive error management in Golang applications.