Add a handler to make the structure of validation errors consistent.

This commit is contained in:
2025-11-16 12:26:47 +02:00
parent 763773ee51
commit 59caa6a0ab
3 changed files with 34 additions and 3 deletions
+31
View File
@@ -1,4 +1,5 @@
from fastapi import FastAPI, HTTPException, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.requests import Request
from typing import List, Optional, Union, Dict, Any, Tuple
@@ -71,6 +72,36 @@ async def http_exception_handler(request: Request, exc: HTTPException):
content=response_body
)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
"""
Handles Pydantic validation errors (normally 422) and returns them as 400 Bad Request
with a consistent error structure.
Return first validation error.
"""
# Extract validation error details
errors = exc.errors()
# Get first error:
location = " -> ".join(str(l) for l in errors[0]["loc"])
error_message = f"{location}: {errors[0]['msg']}"
response_body = {
"error": {
"code": "INVALID_INPUT",
"message": error_message,
"details": {}
}
}
return JSONResponse(
# Changed from 422 to 400
status_code=400,
content=response_body
)
# ==================== Endpoints ====================
@app.get("/health")
async def health_check():