Green: convert 422 to 400 on input errors
This commit is contained in:
parent
c058c7513c
commit
df1dbbbc18
21
dev.py
21
dev.py
|
@ -1,4 +1,6 @@
|
|||
from fastapi import FastAPI, Depends, Request, HTTPException
|
||||
from fastapi import FastAPI, Depends, Request, HTTPException, status
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
|
@ -10,6 +12,23 @@ import schemas
|
|||
|
||||
app = FastAPI()
|
||||
|
||||
convert_422_to_400 = True
|
||||
|
||||
|
||||
if convert_422_to_400:
|
||||
# Taken from there.
|
||||
# https://stackoverflow.com/questions/75958222/can-i-return-400-error-instead-of-422-error
|
||||
# https://stackoverflow.com/questions/71681068/how-to-customise-error-response-for-a-specific-route-in-fastapi
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(
|
||||
request: Request, exc: RequestValidationError
|
||||
):
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
content={"detail": exc.errors()},
|
||||
)
|
||||
|
||||
|
||||
# Dependency
|
||||
def get_db():
|
||||
|
|
Loading…
Reference in New Issue