Skip to content

Commit e1527b2

Browse files
committed
Add validation exception handler with optional debug logging
1 parent 1c2823a commit e1527b2

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

nwastdlib/logging.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,15 @@
1616
from typing import Any, Union
1717

1818
import structlog
19+
from fastapi import Request
20+
from fastapi.exceptions import RequestValidationError
21+
from fastapi.responses import JSONResponse
22+
from starlette import status
23+
24+
from nwastdlib.settings import nwa_settings
25+
26+
logger = structlog.get_logger(__name__)
27+
1928

2029
pre_chain = [
2130
structlog.contextvars.merge_contextvars,
@@ -119,3 +128,12 @@ def __init__(self, app): # type: ignore
119128
async def __call__(self, scope, receive, send): # type: ignore
120129
structlog.contextvars.clear_contextvars()
121130
await self.app(scope, receive, send)
131+
132+
133+
async def validation_exception_handler(request: Request, exc: RequestValidationError):
134+
exc_str = f"{exc}".replace("\n", " ").replace(" ", " ")
135+
if nwa_settings.DEBUG:
136+
method, url, headers, body = request.method, request.url, request.headers, await request.json()
137+
logger.debug("Validation error in endpoint", method=method, url=url, headers=headers, body=body, error=exc_str)
138+
content = {"status_code": 422, "message": exc_str, "data": None}
139+
return JSONResponse(content=content, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY)

0 commit comments

Comments
 (0)