| 1 |
from collections.abc import Callable |
| 2 |
|
| 3 |
from fastapi import Body, FastAPI, HTTPException, Request, Response |
| 4 |
from fastapi.exceptions import RequestValidationError |
| 5 |
from fastapi.routing import APIRoute |
| 6 |
|
| 7 |
|
| 8 |
class ValidationErrorLoggingRoute(APIRoute): |
| 9 |
def get_route_handler(self) -> Callable: |
| 10 |
original_route_handler = super().get_route_handler() |
| 11 |
|
| 12 |
async def custom_route_handler(request: Request) -> Response: |
| 13 |
try: |
| 14 |
return await original_route_handler(request) |
| 15 |
except RequestValidationError as exc: |
| 16 |
body = await request.body() |
| 17 |
detail = {"errors": exc.errors(), "body": body.decode()} |
| 18 |
raise HTTPException(status_code=422, detail=detail) |
| 19 |
|
| 20 |
return custom_route_handler |
| 21 |
|
| 22 |
|
| 23 |
app = FastAPI() |
| 24 |
app.router.route_class = ValidationErrorLoggingRoute |
| 25 |
|
| 26 |
|
| 27 |
@app.post("/") |
| 28 |
async def sum_numbers(numbers: list[int] = Body()): |
| 29 |
return sum(numbers) |