How to replace 422 standard exception with custom exception only for one route in FastAPI?
I don't want to replace for the application project, just for one route. I read many docs, and I don't understand how to do this.
Example of route that I need to change the 422 exception:
from fastapi import APIRouter
from pydantic import BaseModel
router = APIRouter()
class PayloadSchema(BaseModel):
value_int: int
value_str: str
@router.post('/custom')
async def custom_route(payload: PayloadSchema):
return payload
You can register multiple error handlers with the router. You can re-declare the default handler, and then optionally call it depending on the path:
Or you can do it directly with the
@app.exception_handlerdecorator without the router (see FastAPI docs).