|
16 | 16 | from typing import Any, Union
|
17 | 17 |
|
18 | 18 | 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 | + |
19 | 28 |
|
20 | 29 | pre_chain = [
|
21 | 30 | structlog.contextvars.merge_contextvars,
|
@@ -119,3 +128,12 @@ def __init__(self, app): # type: ignore
|
119 | 128 | async def __call__(self, scope, receive, send): # type: ignore
|
120 | 129 | structlog.contextvars.clear_contextvars()
|
121 | 130 | 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