Error Handling Techniques
Understanding Network Error Types
Network errors can occur at various stages of request-response lifecycle:
Error Category |
Description |
Common Causes |
Connection Errors |
Failure to establish network connection |
Network unavailability, DNS issues |
Timeout Errors |
Request exceeds maximum waiting time |
Slow server, network congestion |
HTTP Errors |
Server returns error status codes |
Authentication failure, resource not found |
Parsing Errors |
Unable to process response data |
Malformed JSON/XML, unexpected data format |
Comprehensive Error Handling Strategy
graph TD
A[Network Request] --> B{Request Successful?}
B -->|Yes| C[Process Response]
B -->|No| D[Implement Error Handling]
D --> E{Error Type}
E -->|Connection| F[Retry Connection]
E -->|Timeout| G[Implement Backoff Strategy]
E -->|HTTP Error| H[Handle Specific Status Code]
E -->|Parsing| I[Fallback/Log Error]
Python Error Handling Techniques
Robust Request Handling
import requests
from requests.exceptions import RequestException, ConnectionError, Timeout
def resilient_network_request(url, max_retries=3):
for attempt in range(max_retries):
try:
response = requests.get(url, timeout=5)
response.raise_for_status() ## Raise exception for bad status codes
return response.json()
except ConnectionError:
print(f"Connection failed, retry {attempt + 1}")
continue
except Timeout:
print(f"Request timed out, retry {attempt + 1}")
continue
except RequestException as e:
print(f"Request error: {e}")
break
return None
Advanced Error Logging
import logging
logging.basicConfig(
level=logging.ERROR,
format='%(asctime)s - %(levelname)s: %(message)s'
)
def log_network_errors(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
logging.error(f"Network operation failed: {e}")
raise
return wrapper
Error Handling Best Practices
Exponential Backoff Strategy
import time
import random
def exponential_backoff(attempt, base_delay=1):
"""Generate increasing delay between retries"""
delay = base_delay * (2 ** attempt) + random.uniform(0, 1)
time.sleep(delay)
Comprehensive Exception Handling
def handle_network_response(response):
try:
## Validate response
if not response.ok:
raise ValueError(f"Bad response: {response.status_code}")
data = response.json()
## Additional validation
if not data:
raise ValueError("Empty response")
return data
except ValueError as ve:
print(f"Validation Error: {ve}")
except Exception as e:
print(f"Unexpected error: {e}")
LabEx Recommended Patterns
At LabEx, we emphasize:
- Implement multiple layers of error handling
- Use context managers
- Log errors comprehensively
- Design graceful degradation mechanisms
Advanced Error Mitigation Techniques
- Circuit Breaker Pattern
- Retry with Jittered Backoff
- Fallback Mechanism
- Comprehensive Logging
- Minimize retry attempts
- Set reasonable timeout values
- Use structured logging
- Monitor and analyze error patterns