Error Handling Strategies
Comprehensive Timeout Error Management
1. Basic Error Handling Pattern
func robustTimeoutHandler() error {
ch := make(chan int, 1)
select {
case result := <-ch:
return processResult(result)
case <-time.After(3 * time.Second):
return fmt.Errorf("operation timed out after 3 seconds")
}
}
Error Handling Flow
flowchart TD
A[Start Operation] --> B{Timeout Occurred?}
B -->|Yes| C[Generate Error]
B -->|No| D[Process Result]
C --> E[Log Error]
C --> F[Retry/Fallback]
D --> G[Complete Operation]
Error Types and Handling Strategies
Error Type |
Handling Strategy |
Example |
Timeout Error |
Retry/Fallback |
Reconnect to service |
Network Error |
Exponential Backoff |
Incremental delay |
Resource Exhaustion |
Circuit Breaker |
Temporary service suspension |
2. Advanced Error Handling with Context
func sophisticatedErrorHandling() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
errChan := make(chan error, 1)
go func() {
err := performCriticalOperation(ctx)
if err != nil {
errChan <- err
}
}()
select {
case err := <-errChan:
handleSpecificError(err)
case <-ctx.Done():
switch ctx.Err() {
case context.DeadlineExceeded:
log.Println("Operation timed out")
case context.Canceled:
log.Println("Operation was canceled")
}
}
}
Custom Error Wrapper
type TimeoutError struct {
Operation string
Duration time.Duration
Err error
}
func (e *TimeoutError) Error() string {
return fmt.Sprintf("operation %s timed out after %v: %v",
e.Operation, e.Duration, e.Err)
}
Retry Mechanism with Advanced Error Handling
func retryWithErrorHandling(maxRetries int) error {
for attempt := 1; attempt <= maxRetries; attempt++ {
err := executeOperationWithTimeout()
if err == nil {
return nil
}
if isRecoverableError(err) {
backoffDuration := calculateBackoff(attempt)
time.Sleep(backoffDuration)
continue
}
return &TimeoutError{
Operation: "critical-operation",
Duration: 5 * time.Second,
Err: err,
}
}
return errors.New("max retries exceeded")
}
Best Practices
- Create custom error types
- Implement detailed logging
- Use context for timeout management
- Provide meaningful error messages
- Consider LabEx's error tracking capabilities
Error Handling Principles
- Always handle potential timeout scenarios
- Implement graceful degradation
- Provide clear error information
- Use structured error handling
- Minimize performance overhead
- Lightweight error objects
- Efficient error checking
- Minimal allocation overhead
- Quick error propagation mechanisms