unraisablehook.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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() -> None:
  16. sys.unraisablehook = _make_unraisable(sys.unraisablehook)
  17. def _make_unraisable(
  18. old_unraisablehook: "Callable[[sys.UnraisableHookArgs], Any]",
  19. ) -> "Callable[[sys.UnraisableHookArgs], Any]":
  20. def sentry_sdk_unraisablehook(unraisable: "sys.UnraisableHookArgs") -> None:
  21. integration = sentry_sdk.get_client().get_integration(UnraisablehookIntegration)
  22. # Note: If we replace this with ensure_integration_enabled then
  23. # we break the exceptiongroup backport;
  24. # See: https://github.com/getsentry/sentry-python/issues/3097
  25. if integration is None:
  26. return old_unraisablehook(unraisable)
  27. if unraisable.exc_value and unraisable.exc_traceback:
  28. with capture_internal_exceptions():
  29. event, hint = event_from_exception(
  30. (
  31. unraisable.exc_type,
  32. unraisable.exc_value,
  33. unraisable.exc_traceback,
  34. ),
  35. client_options=sentry_sdk.get_client().options,
  36. mechanism={"type": "unraisablehook", "handled": False},
  37. )
  38. sentry_sdk.capture_event(event, hint=hint)
  39. return old_unraisablehook(unraisable)
  40. return sentry_sdk_unraisablehook