|
| 1 | +import sentry_sdk |
| 2 | +from sentry_sdk.utils import ( |
| 3 | + capture_internal_exceptions, |
| 4 | + event_from_exception, |
| 5 | +) |
| 6 | +from sentry_sdk.integrations import Integration, DidNotEnable |
| 7 | + |
| 8 | +from typing import TYPE_CHECKING |
| 9 | + |
| 10 | +if TYPE_CHECKING: |
| 11 | + from typing import Callable |
| 12 | + from typing import Any |
| 13 | + from typing import Type |
| 14 | + from typing import Optional |
| 15 | + |
| 16 | + from types import TracebackType |
| 17 | + |
| 18 | + Excepthook = Callable[ |
| 19 | + [Type[BaseException], BaseException, Optional[TracebackType]], |
| 20 | + Any, |
| 21 | + ] |
| 22 | + |
| 23 | +try: |
| 24 | + import typer |
| 25 | +except ImportError: |
| 26 | + raise DidNotEnable("Typer not installed") |
| 27 | + |
| 28 | + |
| 29 | +class TyperIntegration(Integration): |
| 30 | + identifier = "typer" |
| 31 | + |
| 32 | + @staticmethod |
| 33 | + def setup_once(): |
| 34 | + # type: () -> None |
| 35 | + typer.main.except_hook = _make_excepthook(typer.main.except_hook) # type: ignore |
| 36 | + |
| 37 | + |
| 38 | +def _make_excepthook(old_excepthook): |
| 39 | + # type: (Excepthook) -> Excepthook |
| 40 | + def sentry_sdk_excepthook(type_, value, traceback): |
| 41 | + # type: (Type[BaseException], BaseException, Optional[TracebackType]) -> None |
| 42 | + integration = sentry_sdk.get_client().get_integration(TyperIntegration) |
| 43 | + |
| 44 | + # Note: If we replace this with ensure_integration_enabled then |
| 45 | + # we break the exceptiongroup backport; |
| 46 | + # See: https://github.com/getsentry/sentry-python/issues/3097 |
| 47 | + if integration is None: |
| 48 | + return old_excepthook(type_, value, traceback) |
| 49 | + |
| 50 | + with capture_internal_exceptions(): |
| 51 | + event, hint = event_from_exception( |
| 52 | + (type_, value, traceback), |
| 53 | + client_options=sentry_sdk.get_client().options, |
| 54 | + mechanism={"type": "typer", "handled": False}, |
| 55 | + ) |
| 56 | + sentry_sdk.capture_event(event, hint=hint) |
| 57 | + |
| 58 | + return old_excepthook(type_, value, traceback) |
| 59 | + |
| 60 | + return sentry_sdk_excepthook |
0 commit comments