Skip to content

Commit

Permalink
Merge pull request #77 from Alexander-N/client-disconnect
Browse files Browse the repository at this point in the history
Use status code 499 for requests where the client closed the connection
  • Loading branch information
stephenhillier committed Oct 21, 2023
2 parents 0de22e7 + 6ddd95f commit 6863016
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions starlette_exporter/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,9 +256,7 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
# Increment requests_in_progress gauge when request comes in
self.requests_in_progress.labels(method, self.app_name, *default_labels).inc()

# Default status code used when the application does not return a valid response
# or an unhandled exception occurs.
status_code = 500
status_code = None

# optional request and response body size metrics
response_body_size: int = 0
Expand Down Expand Up @@ -308,6 +306,9 @@ async def wrapped_send(message: Message) -> None:

try:
await self.app(scope, receive, wrapped_send)
except Exception:
status_code = 500
raise
finally:
# Decrement 'requests_in_progress' gauge after response sent
self.requests_in_progress.labels(
Expand All @@ -327,6 +328,14 @@ async def wrapped_send(message: Message) -> None:
if self.group_paths and grouped_path is not None:
path = grouped_path

if status_code is None:
request = Request(scope, receive)
if await request.is_disconnected():
# In case no response was returned and the client is disconnected, 499 is reported as status code.
status_code = 499
else:
logger.error("Unexpected error: Application did not return a valid response")
status_code = 500
labels = [method, path, status_code, self.app_name, *default_labels]

# optional extra arguments to be passed as kwargs to observations
Expand Down

0 comments on commit 6863016

Please sign in to comment.