Skip to content

Commit 942be48

Browse files
committed
feat: Add serverless integration
1 parent 8418fd1 commit 942be48

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed

sentry_sdk/integrations/serverless.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import functools
2+
import sys
3+
4+
from sentry_sdk import Hub
5+
from sentry_sdk.utils import event_from_exception
6+
from sentry_sdk._compat import reraise
7+
8+
9+
def serverless_function(f=None, flush=True):
10+
def wrapper(f):
11+
@functools.wraps(f)
12+
def inner(*args, **kwargs):
13+
try:
14+
return f(*args, **kwargs)
15+
except Exception:
16+
_capture_and_reraise()
17+
finally:
18+
if flush:
19+
_flush_client()
20+
21+
return inner
22+
23+
if f is None:
24+
return wrapper
25+
else:
26+
return wrapper(f)
27+
28+
29+
def _capture_and_reraise():
30+
exc_info = sys.exc_info()
31+
hub = Hub.current
32+
if hub is not None and hub.client is not None:
33+
event, hint = event_from_exception(
34+
exc_info,
35+
client_options=hub.client.options,
36+
mechanism={"type": "serverless", "handled": False},
37+
)
38+
hub.capture_event(event, hint=hint)
39+
40+
reraise(*exc_info)
41+
42+
43+
def _flush_client():
44+
hub = Hub.current
45+
if hub is not None:
46+
hub.flush()
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import pytest
2+
3+
from sentry_sdk.integrations.serverless import serverless_function
4+
5+
6+
def test_basic(sentry_init, capture_exceptions, monkeypatch):
7+
sentry_init()
8+
exceptions = capture_exceptions()
9+
10+
flush_calls = []
11+
12+
monkeypatch.setattr("sentry_sdk.Hub.current.flush", lambda: flush_calls.append(1))
13+
14+
@serverless_function
15+
def foo():
16+
1 / 0
17+
18+
with pytest.raises(ZeroDivisionError):
19+
foo()
20+
21+
exception, = exceptions
22+
assert isinstance(exception, ZeroDivisionError)
23+
24+
assert flush_calls == [1]
25+
26+
27+
def test_flush_disabled(sentry_init, capture_exceptions, monkeypatch):
28+
sentry_init()
29+
exceptions = capture_exceptions()
30+
31+
flush_calls = []
32+
33+
monkeypatch.setattr("sentry_sdk.Hub.current.flush", lambda: flush_calls.append(1))
34+
35+
@serverless_function(flush=False)
36+
def foo():
37+
1 / 0
38+
39+
with pytest.raises(ZeroDivisionError):
40+
foo()
41+
42+
exception, = exceptions
43+
assert isinstance(exception, ZeroDivisionError)
44+
45+
assert flush_calls == []

0 commit comments

Comments
 (0)