Error Handling Strategies
Timeout Error Classification
graph TD
A[Timeout Errors] --> B[Network Errors]
A --> C[Resource Exhaustion]
A --> D[Cascading Failures]
Comprehensive Error Handling Pattern
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
)
}
func performRequestWithAdvancedErrorHandling() error {
ctx, cancel := context.WithTimeout(
context.Background(),
5 * time.Second
)
defer cancel()
result := make(chan string, 1)
go func() {
// Simulate network request
time.Sleep(6 * time.Second)
result <- "Completed"
}()
select {
case data := <-result:
fmt.Println(data)
return nil
case <-ctx.Done():
return &TimeoutError{
Operation: "NetworkRequest",
Duration: 5 * time.Second,
Err: ctx.Err(),
}
}
}
Error Handling Strategies
Strategy |
Description |
Use Case |
Retry Mechanism |
Automatically retry failed operations |
Transient network errors |
Fallback Response |
Provide default response |
Non-critical operations |
Circuit Breaker |
Prevent repeated failures |
Distributed systems |
Graceful Degradation |
Reduce functionality |
Partial service availability |
Retry Mechanism Implementation
func retryOperation(
maxRetries int,
operation func() error
) error {
var lastErr error
for attempt := 0; attempt < maxRetries; attempt++ {
err := operation()
if err == nil {
return nil
}
lastErr = err
// Exponential backoff
backoffDuration := time.Duration(
math.Pow(2, float64(attempt))) * time.Second
time.Sleep(backoffDuration)
}
return fmt.Errorf(
"operation failed after %d attempts: %v",
maxRetries,
lastErr
)
}
Advanced Error Logging
func logTimeoutError(err error) {
switch e := err.(type) {
case *TimeoutError:
log.Printf(
"Timeout Error: Operation %s failed after %v",
e.Operation,
e.Duration
)
case net.Error:
if e.Timeout() {
log.Println("Network timeout occurred")
}
default:
log.Println("Unknown error type")
}
}
Best Practices
- Create custom error types
- Implement structured logging
- Use context for timeout propagation
- Design resilient error recovery mechanisms
By mastering these error handling strategies, developers can build more robust applications using LabEx's recommended approaches to managing timeout-related challenges.