Handle exceptions¶
With handle_exceptions=False, override_validation_error doesn't register an exception handler and only patches the schema. The response comes from your own handler:
@app.exception_handler(RequestValidationError)
async def validation_handler(
request: Request, exc: RequestValidationError
) -> JSONResponse:
return JSONResponse(
status_code=400,
content={"message": "Validation failed", "errors": exc.errors()},
)
override_validation_error(app, handle_exceptions=False)
A request that fails validation gets your handler's response, here 400 with {"message": "Validation failed", "errors": [...]}, and the schema documents the validation error at 400.
The schema still documents FastAPI's HTTPValidationError body, {"detail": [...]}, which this handler doesn't send. To change the body and its schema together, use an error builder instead, which can't be combined with handle_exceptions=False.
Your handler also has to use the same status code and, if you set one, the same media_type: the library doesn't check them.