unraisablehook.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import sys
  2. import sentry_sdk
  3. from sentry_sdk.utils import (
  4. capture_internal_exceptions,
  5. event_from_exception,
  6. )
  7. from sentry_sdk.integrations import Integration
  8. from typing import TYPE_CHECKING
  9. if TYPE_CHECKING:
  10. from typing import Callable
  11. from typing import Any
  12. class UnraisablehookIntegration(Integration):
  13. identifier = "unraisablehook"
  14. @staticmethod
  15. def setup_once():
  16. # type: () -> None
  17. sys.unraisablehook = _make_unraisable(sys.unraisablehook)
  18. def _make_unraisable(old_unraisablehook):
  19. # type: (Callable[[sys.UnraisableHookArgs], Any]) -> Callable[[sys.UnraisableHookArgs], Any]
  20. def sentry_sdk_unraisablehook(unraisable):
  21. # type: (sys.UnraisableHookArgs) -> None
  22. integration = sentry_sdk.get_client().get_integration(UnraisablehookIntegration)
  23. # Note: If we replace this with ensure_integration_enabled then
  24. # we break the exceptiongroup backport;
  25. # See: https://github.com/getsentry/sentry-python/issues/3097
  26. if integration is None:
  27. return old_unraisablehook(unraisable)
  28. if unraisable.exc_value and unraisable.exc_traceback:
  29. with capture_internal_exceptions():
  30. event, hint = event_from_exception(
  31. (
  32. unraisable.exc_type,
  33. unraisable.exc_value,
  34. unraisable.exc_traceback,
  35. ),
  36. client_options=sentry_sdk.get_client().options,
  37. mechanism={"type": "unraisablehook", "handled": False},
  38. )
  39. sentry_sdk.capture_event(event, hint=hint)
  40. return old_unraisablehook(unraisable)
  41. return sentry_sdk_unraisablehook