Bird
0
0

Why does this custom validation error handler fail to catch errors?

medium📝 Debug Q7 of 15
FastAPI - Error Handling
Why does this custom validation error handler fail to catch errors? ```python from fastapi import FastAPI from fastapi.exceptions import ValidationError from fastapi.responses import JSONResponse app = FastAPI() @app.exception_handler(ValidationError) async def custom_handler(request, exc): return JSONResponse(status_code=422, content={'detail': 'Custom error'}) ```
AJSONResponse is not suitable for error responses
BThe handler must be synchronous, not async
CIt should catch RequestValidationError, not ValidationError
DThe exception handler decorator is missing parentheses
Step-by-Step Solution
Solution:
  1. Step 1: Identify the correct exception for FastAPI validation errors

    FastAPI raises RequestValidationError, not ValidationError, for request validation issues.
  2. Step 2: Understand why the handler does not catch errors

    Because the handler listens for ValidationError, it misses RequestValidationError exceptions.
  3. Final Answer:

    It should catch RequestValidationError, not ValidationError -> Option C
  4. Quick Check:

    Use RequestValidationError to catch validation errors [OK]
Quick Trick: Catch RequestValidationError, not ValidationError, for FastAPI validation [OK]
Common Mistakes:
MISTAKES
  • Using ValidationError instead of RequestValidationError
  • Thinking async handlers are invalid
  • Misusing JSONResponse for error handling

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes