Practical Error Management
Comprehensive Error Handling Approach
Error Flow and Decision Making
graph TD
A[Error Occurrence] --> B{Error Type}
B --> |Recoverable| C[Log and Handle]
B --> |Critical| D[Graceful Shutdown]
B --> |Operational| E[Retry Mechanism]
Error Logging Strategies
Structured Logging Techniques
type LogEntry struct {
Level string
Message string
Timestamp time.Time
Error error
}
func logError(entry LogEntry) {
log.Printf("[%s] %s: %v",
entry.Level,
entry.Message,
entry.Error)
}
Error Handling Patterns
Pattern |
Use Case |
Implementation |
Retry |
Transient Errors |
Exponential backoff |
Fallback |
Service Unavailable |
Default response |
Circuit Breaker |
Prevent System Overload |
Temporary service suspension |
Advanced Error Management Example
func executeWithRetry(operation func() error, maxRetries int) error {
var lastErr error
for attempt := 0; attempt < maxRetries; attempt++ {
if err := operation(); err != nil {
lastErr = err
backoffDuration := time.Second * time.Duration(math.Pow(2, float64(attempt)))
time.Sleep(backoffDuration)
continue
}
return nil
}
return fmt.Errorf("operation failed after %d attempts: %w", maxRetries, lastErr)
}
Error Handling in Main Function
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
if err := runApplication(ctx); err != nil {
switch {
case errors.Is(err, context.DeadlineExceeded):
fmt.Println("Application timed out")
case errors.Is(err, context.Canceled):
fmt.Println("Application canceled")
default:
fmt.Printf("Application error: %v\n", err)
}
os.Exit(1)
}
}
Error Monitoring and Reporting
Telemetry Integration
func reportErrorToMonitoringSystem(err error) {
errorDetails := struct {
Message string
Stack string
Time time.Time
}{
Message: err.Error(),
Stack: string(debug.Stack()),
Time: time.Now(),
}
// Send to monitoring system
monitoring.Report(errorDetails)
}
Best Practices
- Create meaningful error messages
- Use error wrapping for context
- Implement appropriate error handling strategies
- Log errors with sufficient detail
- Use context for timeout and cancellation
LabEx recommends developing a systematic approach to error management that balances robustness and simplicity in Go applications.