File tree Expand file tree Collapse file tree 1 file changed +19
-0
lines changed Expand file tree Collapse file tree 1 file changed +19
-0
lines changed Original file line number Diff line number Diff line change 45
45
WebSocket ,
46
46
WebSocketDisconnect ,
47
47
)
48
+ from fastapi .exceptions import RequestValidationError
48
49
from fastapi .background import BackgroundTasks
49
50
from fastapi .middleware .cors import CORSMiddleware
50
51
from fastapi .responses import JSONResponse , RedirectResponse , StreamingResponse
@@ -290,6 +291,24 @@ async def validation_exception_handler(_request: Request, exc: ValidationError):
290
291
return JSONResponse (status_code = 422 , content = ErrorFormatter .format_validation_error (exc ))
291
292
292
293
294
+ @app .exception_handler (RequestValidationError )
295
+ async def request_validation_exception_handler (_request : Request , exc : RequestValidationError ):
296
+ """Handle FastAPI request validation errors globally.
297
+
298
+ Intercepts RequestValidationError exceptions raised by FastAPI's automatic
299
+ request validation and returns a properly formatted JSON error response.
300
+ This ensures that user input is not reflected back in error messages.
301
+
302
+ Args:
303
+ _request: The FastAPI request object that triggered the validation error.
304
+ exc: The FastAPI RequestValidationError exception.
305
+
306
+ Returns:
307
+ JSONResponse: A 422 Unprocessable Entity response with sanitized error details.
308
+ """
309
+ return JSONResponse (status_code = 422 , content = ErrorFormatter .format_validation_error (exc ))
310
+
311
+
293
312
@app .exception_handler (IntegrityError )
294
313
async def database_exception_handler (_request : Request , exc : IntegrityError ):
295
314
"""Handle SQLAlchemy database integrity constraint violations globally.
You can’t perform that action at this time.
0 commit comments