-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexceptions.py
89 lines (63 loc) · 2.61 KB
/
exceptions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"""Custom exceptions for the Keywords4CV application."""
class ConfigError(Exception):
"""Raised when there is an error in the configuration."""
pass
class InputValidationError(Exception):
"""Raised when there is an error in the input data."""
pass
class DataIntegrityError(Exception):
"""Raised when there is an error in the data integrity."""
pass
class APIError(Exception):
"""Raised when there is an error in API communication."""
pass
class NetworkError(Exception):
"""Raised when there is a network error."""
pass
class AuthenticationError(Exception):
"""Raised when there is an authentication error."""
pass
class SimpleCircuitBreaker:
"""A simple circuit breaker implementation."""
def __init__(self, failure_threshold=5, recovery_timeout=60):
"""
Initialize the circuit breaker.
Args:
failure_threshold: Number of failures before opening the circuit
recovery_timeout: Time in seconds to wait before attempting recovery
"""
self.failure_threshold = failure_threshold
self.recovery_timeout = recovery_timeout
self.failure_count = 0
self.last_failure_time = None
self.state = "CLOSED" # CLOSED, OPEN, HALF-OPEN
def __call__(self, func):
"""Decorator to wrap a function with circuit breaker logic."""
def wrapper(*args, **kwargs):
if self.state == "OPEN":
# Check if recovery timeout has elapsed
if (
self.last_failure_time
and time.time() - self.last_failure_time > self.recovery_timeout
):
self.state = "HALF-OPEN"
else:
raise NetworkError("Circuit breaker is open")
try:
result = func(*args, **kwargs)
if self.state == "HALF-OPEN":
# Success, close the circuit
self.failure_count = 0
self.state = "CLOSED"
return result
except (APIError, NetworkError) as e:
# Only count API and Network errors
self.failure_count += 1
self.last_failure_time = time.time()
if self.failure_count >= self.failure_threshold:
self.state = "OPEN"
raise e
except Exception as e:
# Don't count other exceptions towards circuit breaker
raise e
return wrapper