11import contextvars
22from contextlib import contextmanager
33from typing import Any , Callable , Dict , TypeVar , cast
4+ from posthog import capture_exception
45
56_context_stack : contextvars .ContextVar [list ] = contextvars .ContextVar ("posthog_context_stack" , default = [{}])
67
@@ -15,30 +16,24 @@ def new_context():
1516 # but right now it only applies to exceptions...
1617 """
1718 Create a new context scope that will be active for the duration of the with block.
18- Any tags set within this scope will be isolated to this context. Tags added to a
19- context will be added to exceptions captured within that context.
20-
21- NOTE: tags set within a context will only be added to exceptions captured within that
22- context - ensure you call `posthog.capture_exception()` before the end of the with
23- block, or the extra tags will be lost.
24-
25- It's strongly recommended to use the `posthog.tracked` decorator to instrument functions, rather
26- than directly using this context manager.
19+ Any tags set within this scope will be isolated to this context. Any exceptions raised
20+ within the context will be captured and tagged with the context tags.
2721
2822 Example:
2923 with posthog.new_context():
3024 posthog.tag("user_id", "123")
31- try:
32- # Do something that might raise an exception
33- except Exception as e:
34- posthog.capture_exception(e)
35- raise e
25+ # The exception will be captured and tagged with the context tags
26+ raise ValueError("Something went wrong")
27+
3628 """
3729 current_stack = _context_stack .get ()
3830 new_stack = current_stack + [{}]
3931 token = _context_stack .set (new_stack )
4032 try :
4133 yield
34+ except Exception as e :
35+ capture_exception (e )
36+ raise
4237 finally :
4338 _context_stack .reset (token )
4439
@@ -80,8 +75,7 @@ def scoped(func: F) -> F:
8075 """
8176 Decorator that creates a new context for the function, wraps the function in a
8277 try/except block, and if an exception occurs, captures it with the current context
83- tags before re-raising it. This is the recommended way to wrap/track functions for
84- posthog error tracking.
78+ tags before re-raising it.
8579
8680 Args:
8781 func: The function to wrap
@@ -96,17 +90,10 @@ def process_payment(payment_id):
9690 """
9791 from functools import wraps
9892
99- import posthog
100-
10193 @wraps (func )
10294 def wrapper (* args , ** kwargs ):
10395 with new_context ():
104- try :
105- return func (* args , ** kwargs )
106- except Exception as e :
107- # Capture the exception with current context tags
108- # The capture_exception function will handle deduplication
109- posthog .capture_exception (e , properties = get_tags ())
110- raise # Re-raise the exception after capturing it
96+ return func (* args , ** kwargs )
97+
11198
11299 return cast (F , wrapper )
0 commit comments