Skip to content

Commit 45976fa

Browse files
committed
added predicate
1 parent e9f2f67 commit 45976fa

File tree

1 file changed

+35
-1
lines changed

1 file changed

+35
-1
lines changed

packages/service-library/src/servicelib/exception_utils.py

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,8 +77,34 @@ def else_reset(self) -> None:
7777

7878

7979
def suppress_exceptions(
80-
exceptions: tuple[type[BaseException], ...], *, reason: str
80+
exceptions: tuple[type[BaseException], ...],
81+
*,
82+
reason: str,
83+
predicate: Callable[[BaseException], bool] | None = None,
8184
) -> Callable[[F], F]:
85+
"""
86+
Decorator to suppress specified exceptions.
87+
88+
Args:
89+
exceptions: Tuple of exception types to suppress
90+
reason: Reason for suppression (for logging)
91+
predicate: Optional function to check exception attributes.
92+
If provided, exception is only suppressed if predicate returns True.
93+
94+
Example:
95+
# Suppress all ConnectionError exceptions
96+
@suppress_exceptions((ConnectionError,), reason="Network issues")
97+
def my_func(): ...
98+
99+
# Suppress only ConnectionError with specific errno
100+
@suppress_exceptions(
101+
(ConnectionError,),
102+
reason="Specific network error",
103+
predicate=lambda e: hasattr(e, 'errno') and e.errno == 104
104+
)
105+
def my_func(): ...
106+
"""
107+
82108
def _decorator(func_or_coro: F) -> F:
83109
if inspect.iscoroutinefunction(func_or_coro):
84110

@@ -88,6 +114,10 @@ async def _async_wrapper(*args, **kwargs) -> Any:
88114
assert inspect.iscoroutinefunction(func_or_coro) # nosec
89115
return await func_or_coro(*args, **kwargs)
90116
except exceptions as exc:
117+
# Check predicate if provided
118+
if predicate is not None and not predicate(exc):
119+
raise # Re-raise if predicate returns False
120+
91121
_logger.debug(
92122
"Caught suppressed exception %s in %s: TIP: %s",
93123
exc,
@@ -103,6 +133,10 @@ def _sync_wrapper(*args, **kwargs) -> Any:
103133
try:
104134
return func_or_coro(*args, **kwargs)
105135
except exceptions as exc:
136+
# Check predicate if provided
137+
if predicate is not None and not predicate(exc):
138+
raise # Re-raise if predicate returns False
139+
106140
_logger.debug(
107141
"Caught suppressed exception %s in %s: TIP: %s",
108142
exc,

0 commit comments

Comments
 (0)