From e1527b2a3ee3e65a80a5895a55cce754375cdd31 Mon Sep 17 00:00:00 2001 From: Tjeerd Verschragen Date: Fri, 8 Nov 2024 12:19:16 +0100 Subject: [PATCH] Add validation exception handler with optional debug logging --- nwastdlib/logging.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/nwastdlib/logging.py b/nwastdlib/logging.py index 659ec56..f886da8 100644 --- a/nwastdlib/logging.py +++ b/nwastdlib/logging.py @@ -16,6 +16,15 @@ from typing import Any, Union import structlog +from fastapi import Request +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse +from starlette import status + +from nwastdlib.settings import nwa_settings + +logger = structlog.get_logger(__name__) + pre_chain = [ structlog.contextvars.merge_contextvars, @@ -119,3 +128,12 @@ def __init__(self, app): # type: ignore async def __call__(self, scope, receive, send): # type: ignore structlog.contextvars.clear_contextvars() await self.app(scope, receive, send) + + +async def validation_exception_handler(request: Request, exc: RequestValidationError): + exc_str = f"{exc}".replace("\n", " ").replace(" ", " ") + if nwa_settings.DEBUG: + method, url, headers, body = request.method, request.url, request.headers, await request.json() + logger.debug("Validation error in endpoint", method=method, url=url, headers=headers, body=body, error=exc_str) + content = {"status_code": 422, "message": exc_str, "data": None} + return JSONResponse(content=content, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY)