From 6ddd95fd72b4d44b8e3cd906184c9fecb59946c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20Niederb=C3=BChl?= Date: Wed, 18 Oct 2023 16:13:02 +0200 Subject: [PATCH] Use status code 499 for requests where the client closed the connection If the client closes the connection before a response was returned, 499 is used as status code as in nginx. --- starlette_exporter/middleware.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/starlette_exporter/middleware.py b/starlette_exporter/middleware.py index 058f0e4..1b2e095 100644 --- a/starlette_exporter/middleware.py +++ b/starlette_exporter/middleware.py @@ -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 @@ -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( @@ -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