Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 2 additions & 7 deletions sentry_sdk/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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")

Expand Down
18 changes: 12 additions & 6 deletions sentry_sdk/integrations/dedupe.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
19 changes: 19 additions & 0 deletions sentry_sdk/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
64 changes: 64 additions & 0 deletions tests/test_basics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
):
Expand Down