Skip to content

Commit 452d9ed

Browse files
authored
Merge pull request singer-io#62 from b-ryan/feature/main-critical-wrapper
Decorator for wrapping main functions with critical log
2 parents cdbf7ed + 7d0d0ff commit 452d9ed

2 files changed

Lines changed: 33 additions & 0 deletions

File tree

singer/utils.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,3 +169,18 @@ def exception_is_4xx(exception):
169169
return False
170170

171171
return 400 <= exception.response.status_code < 500
172+
173+
174+
def handle_top_exception(logger):
175+
"""A decorator that will catch exceptions and log the exception's message
176+
as a CRITICAL log."""
177+
def decorator(fn):
178+
@functools.wraps(fn)
179+
def wrapped(*args, **kwargs):
180+
try:
181+
return fn(*args, **kwargs)
182+
except Exception as exc:
183+
logger.critical(exc)
184+
raise
185+
return wrapped
186+
return decorator

tests/test_utils.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,28 @@
11
import unittest
22
from datetime import datetime as dt
33
from datetime import timezone as tz
4+
import logging
45
import singer.utils as u
56

67

78
class TestFormat(unittest.TestCase):
89
def test_small_years(self):
910
self.assertEqual(u.strftime(dt(90, 1, 1, tzinfo=tz.utc), '%04Y-%m-%dT%H:%M:%S.%fZ'),
1011
"0090-01-01T00:00:00.000000Z")
12+
13+
14+
class TestHandleException(unittest.TestCase):
15+
def setUp(self):
16+
self.logger = logging.getLogger(__name__)
17+
18+
def test_successful_fn(self):
19+
@u.handle_top_exception(self.logger)
20+
def foo():
21+
return 3
22+
self.assertEqual(foo(), 3)
23+
24+
def test_exception_fn(self):
25+
@u.handle_top_exception(self.logger)
26+
def foo():
27+
raise RuntimeError("foo")
28+
self.assertRaises(RuntimeError, foo)

0 commit comments

Comments
 (0)