Skip to content

last_event_id() returns None after SentryAsgiMiddleware.__call__() finished #816

Description

@kamilglod

I'm unable to access last_event_id of SentryAsgiMiddleware on exception handler in Starlette framework.

from sentry_sdk import last_event_id
from sentry_sdk.integrations.asgi import SentryAsgiMiddleware
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route


async def test_endpoint(request):
    raise RuntimeError("test")


def exception_handler(*args, **kwargs):
    return JSONResponse({"last_event_id": last_event_id()})


app = Starlette(
    routes=[Route('/', test_endpoint)],
    exception_handlers={
        Exception: exception_handler,
    }
)
app.add_middleware(SentryAsgiMiddleware)

the problem is probably with usage of Hub's context manager in SentryAsgiMiddleware._run_app() - after throwing exception you are clearing local ContextVar so last_event_id function tries to access wrong Hub instance.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions