|
| 1 | +from types import TracebackType |
| 2 | +from typing import Callable, Optional, Type |
| 3 | + |
| 4 | +import sentry_sdk |
1 | 5 | import typer |
| 6 | +from sentry_sdk.integrations import Integration |
| 7 | +from sentry_sdk.utils import ( |
| 8 | + capture_internal_exceptions, |
| 9 | + event_from_exception, |
| 10 | +) |
2 | 11 |
|
3 | 12 | from .commands.deploy import deploy |
4 | 13 | from .commands.env import env_app |
5 | 14 | from .commands.login import login |
6 | 15 | from .commands.whoami import whoami |
7 | 16 |
|
8 | | -app = typer.Typer(rich_markup_mode="rich") |
| 17 | +ExceptionHandler = Callable[ |
| 18 | + [Type[BaseException], BaseException, Optional[TracebackType]], None |
| 19 | +] |
| 20 | + |
| 21 | + |
| 22 | +def _make_excepthook( |
| 23 | + old_excepthook: ExceptionHandler, |
| 24 | +) -> ExceptionHandler: |
| 25 | + def sentry_sdk_excepthook( |
| 26 | + exc_type: Type[BaseException], |
| 27 | + exc_value: BaseException, |
| 28 | + tb: Optional[TracebackType], |
| 29 | + ) -> None: |
| 30 | + integration = sentry_sdk.get_client().get_integration(TyperIntegration) |
| 31 | + |
| 32 | + if integration is None: |
| 33 | + return old_excepthook(exc_type, exc_value, tb) |
| 34 | + |
| 35 | + with capture_internal_exceptions(): |
| 36 | + event, hint = event_from_exception( |
| 37 | + (exc_type, exc_value, tb), |
| 38 | + client_options=sentry_sdk.get_client().options, |
| 39 | + mechanism={"type": "excepthook", "handled": False}, |
| 40 | + ) |
| 41 | + sentry_sdk.capture_event(event, hint=hint) |
| 42 | + |
| 43 | + return old_excepthook(exc_type, exc_value, tb) |
| 44 | + |
| 45 | + return sentry_sdk_excepthook |
| 46 | + |
| 47 | + |
| 48 | +def patch_typer() -> None: |
| 49 | + typer.main.except_hook = _make_excepthook(typer.main.except_hook) # type: ignore |
| 50 | + |
| 51 | + |
| 52 | +class TyperIntegration(Integration): |
| 53 | + identifier = "typer" |
| 54 | + |
| 55 | + @staticmethod |
| 56 | + def setup_once() -> None: |
| 57 | + patch_typer() |
| 58 | + |
| 59 | + |
| 60 | +sentry_sdk.init( |
| 61 | + dsn="https://230250605ea4b58a0b69c768e9ec1168@o4506985151856640.ingest.us.sentry.io/4508449198899200", |
| 62 | + traces_sample_rate=1.0, |
| 63 | + integrations=[TyperIntegration()], |
| 64 | +) |
| 65 | + |
| 66 | + |
| 67 | +app = typer.Typer() |
9 | 68 |
|
10 | 69 |
|
11 | 70 | # TODO: use the app structure |
|
0 commit comments