Bird
0
0

Which code snippet correctly implements this?

hard🚀 Application Q15 of 15
FastAPI - Error Handling
You want to create a custom exception handler in FastAPI that returns a JSON response with a dynamic message and a 400 status code whenever ValueError is raised. Which code snippet correctly implements this?
Afrom fastapi import FastAPI, Request from fastapi.responses import JSONResponse app = FastAPI() @app.exception_handler(ValueError) async def value_error_handler(request: Request, exc: ValueError): return JSONResponse(content={"error": str(exc)}, status=400)
Bfrom fastapi import FastAPI app = FastAPI() @app.exception_handler(ValueError) def value_error_handler(exc: ValueError): return {"error": str(exc), "status": 400}
Cfrom fastapi import FastAPI, Request app = FastAPI() @app.add_exception_handler(ValueError) async def value_error_handler(request: Request, exc: ValueError): return {"error": str(exc), "status_code": 400}
Dfrom fastapi import FastAPI, Request from fastapi.responses import JSONResponse app = FastAPI() @app.exception_handler(ValueError) async def value_error_handler(request: Request, exc: ValueError): return JSONResponse(status_code=400, content={"error": str(exc)})
Step-by-Step Solution
Solution:
  1. Step 1: Check correct decorator and function signature

    Use @app.exception_handler with async function taking (Request, Exception).
  2. Step 2: Verify JSONResponse usage and status code

    Return JSONResponse with status_code=400 and content with error message.
  3. Step 3: Identify correct option

    from fastapi import FastAPI, Request from fastapi.responses import JSONResponse app = FastAPI() @app.exception_handler(ValueError) async def value_error_handler(request: Request, exc: ValueError): return JSONResponse(status_code=400, content={"error": str(exc)}) matches all requirements exactly.
  4. Final Answer:

    A -> Option D
  5. Quick Check:

    Correct async handler with JSONResponse and status_code=400 = A [OK]
Quick Trick: Use async handler with JSONResponse and status_code param [OK]
Common Mistakes:
MISTAKES
  • Using synchronous handler
  • Missing Request parameter
  • Wrong decorator or status code parameter name
  • Returning dict instead of JSONResponse

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes