Verify reraises in AI integrations
We've started using raise e from None instead of the older reraise, verify and change if necessary.
Wherever we have try-except blocks in the integrations, the most common pattern in the SDK at the moment is
import sys
from sentry_sdk.utils import reraise
try:
...
except Exception:
exc_info = sys.exc_info()
custom_exception_handling_logic()
reraise(*exc_info)
We store the original exception, so that if custom_exception_handling_logic() raises an exception, we do not accidentally re-raise anything other than the original exception. We wouldn't need to store the exception if the exception context were always preserved, but afaik we are defensive here because of bugs in CPython that are still not fully resolved. See https://github.com/python/cpython/issues/108668.
Note that this only works if we reach the reraise(), and if custom_exception_handling_logic() raises, then you have two exceptions and two stacktraces. Both show up in Sentry, but the custom_exception_handling_logic() exception determines the title and is shown first.
This means that a bare raise, in the pattern
from sentry_sdk.utils import reraise
try:
...
except Exception:
custom_exception_handling_logic()
raise
can be problematic, and there are a few integrations in which we have bare raises.
We could wrap the sentry_sdk.utils.CaptureInternalException context manager, with the wrapper
- storing original exception info at the beginning; and
- re-raising the original exception on exit, irrespective of exceptions in
custom_exception_handling_logic().
As a result, we would have a pattern like the following
from sentry_sdk.utils import raise_original_exception
try:
...
except Exception:
with raise_original_exception():
custom_exception_handling_logic()
This is mainly relevant for AI integrations, because the version of custom_exception_handling_logic() in other integrations is trivial enough that we should not expect exceptions.
We repeatedly have exceptions raised in our exception-handling code with AI integrations though, such as https://github.com/getsentry/sentry-python/issues/4718.
Sounds good to me @alexander-alderman-webb, thanks for looking into it.