diff --git a/sentry_sdk/client.py b/sentry_sdk/client.py index 7f84cea140..a26a0f5257 100644 --- a/sentry_sdk/client.py +++ b/sentry_sdk/client.py @@ -38,6 +38,7 @@ capture_internal_exceptions, current_stacktrace, env_to_bool, + event_has_unhandled_exception, format_timestamp, get_before_send_log, get_before_send_metric, @@ -675,13 +676,7 @@ def _update_session_from_event( exceptions = (event.get("exception") or {}).get("values") if exceptions: errored = True - for error in exceptions: - if isinstance(error, AnnotatedValue): - error = error.value or {} - mechanism = error.get("mechanism") - if isinstance(mechanism, Mapping) and mechanism.get("handled") is False: - crashed = True - break + crashed = event_has_unhandled_exception(event) user = event.get("user") diff --git a/sentry_sdk/integrations/dedupe.py b/sentry_sdk/integrations/dedupe.py index a79b05bd29..72c1580c1c 100644 --- a/sentry_sdk/integrations/dedupe.py +++ b/sentry_sdk/integrations/dedupe.py @@ -3,7 +3,11 @@ import sentry_sdk from sentry_sdk.integrations import Integration from sentry_sdk.scope import add_global_event_processor -from sentry_sdk.utils import capture_internal_exceptions, logger +from sentry_sdk.utils import ( + capture_internal_exceptions, + event_has_unhandled_exception, + logger, +) if TYPE_CHECKING: from typing import Optional @@ -30,11 +34,13 @@ def processor(event: "Event", hint: "Optional[Hint]") -> "Optional[Event]": return event exc = exc_info[1] + is_unhandled = event_has_unhandled_exception(event) + seen_state = getattr(exc, "_handled_by_sentry", None) - if getattr(exc, "_handled_by_sentry", False): + if seen_state and (not is_unhandled or seen_state == "unhandled"): logger.info("DedupeIntegration dropped duplicated error event %s", exc) return None - else: - with capture_internal_exceptions(): - exc._handled_by_sentry = True - return event + + with capture_internal_exceptions(): + exc._handled_by_sentry = "unhandled" if is_unhandled else "handled" + return event diff --git a/sentry_sdk/utils.py b/sentry_sdk/utils.py index da15448028..45ddbcffe7 100644 --- a/sentry_sdk/utils.py +++ b/sentry_sdk/utils.py @@ -11,6 +11,7 @@ import time import warnings from collections import namedtuple +from collections.abc import Mapping from contextlib import contextmanager from contextvars import ContextVar from datetime import datetime, timezone @@ -2022,3 +2023,21 @@ def _is_localhost( return True return False + + +def event_has_unhandled_exception(event: "Event") -> bool: + """Return True if any exception in ``event`` has ``mechanism.handled is False``.""" + exceptions = (event.get("exception") or {}).get("values") + if not exceptions: + return False + + for error in exceptions: + if isinstance(error, AnnotatedValue): + error = error.value or {} + if not isinstance(error, Mapping): + continue + mechanism = error.get("mechanism") + if isinstance(mechanism, Mapping) and mechanism.get("handled") is False: + return True + + return False diff --git a/tests/test_basics.py b/tests/test_basics.py index be41c03818..a5c3fd1b6b 100644 --- a/tests/test_basics.py +++ b/tests/test_basics.py @@ -683,6 +683,70 @@ def capture(): assert payload_ref() is None +def test_dedupe_allows_unhandled_after_handled(sentry_init, capture_events): + """Logging or capturing before re-raising must still emit the crash event.""" + import logging + + from sentry_sdk.integrations.logging import LoggingIntegration + + sentry_init( + default_integrations=False, + integrations=[ + LoggingIntegration(event_level=logging.ERROR), + DedupeIntegration(), + ], + ) + events = capture_events() + log = logging.getLogger("test_dedupe_crash") + + exc = ValueError("db down") + with sentry_sdk.new_scope() as scope: + scope._session = sentry_sdk.sessions.Session(release="1.0.0") + try: + raise exc + except ValueError: + log.exception("failed before reraise") + event, hint = sentry_sdk.utils.event_from_exception( + sys.exc_info(), + mechanism={"type": "generic", "handled": False}, + ) + sentry_sdk.capture_event(event, hint=hint) + + # A third capture (handled or unhandled) of the same instance is still deduped. + sentry_sdk.capture_exception(exc) + dup_event, dup_hint = sentry_sdk.utils.event_from_exception( + sys.exc_info(), + mechanism={"type": "generic", "handled": False}, + ) + sentry_sdk.capture_event(dup_event, hint=dup_hint) + + assert scope._session.status == "crashed" + + assert len(events) == 2 + assert events[0]["exception"]["values"][-1]["mechanism"]["handled"] is True + assert events[1]["exception"]["values"][-1]["mechanism"]["handled"] is False + + +def test_dedupe_drops_handled_after_unhandled(sentry_init, capture_events): + """Handled captures after an unhandled crash of the same exc stay deduped.""" + sentry_init() + events = capture_events() + + exc = ValueError("crash first") + try: + raise exc + except ValueError: + event, hint = sentry_sdk.utils.event_from_exception( + sys.exc_info(), + mechanism={"type": "generic", "handled": False}, + ) + sentry_sdk.capture_event(event, hint=hint) + sentry_sdk.capture_exception(exc) + + assert len(events) == 1 + assert events[0]["exception"]["values"][-1]["mechanism"]["handled"] is False + + def test_event_processor_drop_records_client_report( sentry_init, capture_events, capture_record_lost_event_calls ):