Skip to content

Commit

Permalink
feat(aiohttp): Add failed_request_status_codes
Browse files Browse the repository at this point in the history
`failed_request_status_codes` allows users to specify the status codes, whose corresponding `HTTPException` types, should be reported to Sentry. By default, these include 5xx statuses, which is a change from the previous default behavior, where no `HTTPException`s would be reported to Sentry.

Closes #3535
  • Loading branch information
szokeasaurusrex committed Sep 20, 2024
1 parent 64e2977 commit 2adb74e
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions sentry_sdk/integrations/aiohttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@
from aiohttp.web_request import Request
from aiohttp.web_urldispatcher import UrlMappingMatchInfo
from aiohttp import TraceRequestStartParams, TraceRequestEndParams

from collections.abc import Set
from types import SimpleNamespace
from typing import Any
from typing import Optional
Expand All @@ -64,14 +66,20 @@ class AioHttpIntegration(Integration):
identifier = "aiohttp"
origin = f"auto.http.{identifier}"

def __init__(self, transaction_style="handler_name"):
# type: (str) -> None
def __init__(
self,
transaction_style="handler_name", # type: str
*,
failed_request_status_codes=frozenset(range(500, 600)), # type: Set[int]
):
# type: (...) -> None
if transaction_style not in TRANSACTION_STYLE_VALUES:
raise ValueError(
"Invalid value for transaction_style: %s (must be in %s)"
% (transaction_style, TRANSACTION_STYLE_VALUES)
)
self.transaction_style = transaction_style
self._failed_request_status_codes = failed_request_status_codes

@staticmethod
def setup_once():
Expand Down Expand Up @@ -99,7 +107,8 @@ def setup_once():

async def sentry_app_handle(self, request, *args, **kwargs):
# type: (Any, Request, *Any, **Any) -> Any
if sentry_sdk.get_client().get_integration(AioHttpIntegration) is None:
integration = sentry_sdk.get_client().get_integration(AioHttpIntegration)
if integration is None:
return await old_handle(self, request, *args, **kwargs)

weak_request = weakref.ref(request)
Expand Down Expand Up @@ -130,6 +139,13 @@ async def sentry_app_handle(self, request, *args, **kwargs):
response = await old_handle(self, request)
except HTTPException as e:
transaction.set_http_status(e.status_code)

if (
e.status_code
in integration._failed_request_status_codes
):
_capture_exception()

raise
except (asyncio.CancelledError, ConnectionResetError):
transaction.set_status(SPANSTATUS.CANCELLED)
Expand Down

0 comments on commit 2adb74e

Please sign in to comment.