Skip to content

Commit a8f34ab

Browse files
author
manas-shinde
committed
feat : Added new decorator - suppress_exceptions.
1 parent a4b87ac commit a8f34ab

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

decorators/suppress_exceptions.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import functools
2+
import logging
3+
4+
logger = logging.getLogger("decorators.suppress")
5+
6+
7+
def suppress_exceptions(default=None, exceptions=(Exception,), log=True):
8+
"""Suppress specified exceptions and optionally log them."""
9+
def decorator(func):
10+
@functools.wraps(func)
11+
def wrapper(*args, **kwargs):
12+
try:
13+
return func(*args, **kwargs)
14+
except exceptions as e:
15+
if log:
16+
logger.warning(
17+
f"Suppressed exception in {func.__name__}: {e}")
18+
return default
19+
return wrapper
20+
return decorator

tests/test_suppress_exceptions.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from decorators.suppress_exceptions import suppress_exceptions
2+
3+
4+
@suppress_exceptions(default="fallback", exceptions=(ZeroDivisionError,))
5+
def risky_div(x):
6+
return 10 / x
7+
8+
9+
def test_suppress_success():
10+
assert risky_div(2) == 5
11+
12+
13+
def test_suppress_zero_division():
14+
assert risky_div(0) == "fallback"

0 commit comments

Comments
 (0)