Bird
0
0

Given this FastAPI code snippet, what will be the response when a ValueError is raised?

medium📝 component behavior Q13 of 15
FastAPI - Error Handling
Given this FastAPI code snippet, what will be the response when a ValueError is raised?
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel

app = FastAPI()

class ErrorResponse(BaseModel):
    detail: str

@app.exception_handler(ValueError)
async def value_error_handler(request: Request, exc: ValueError):
    return JSONResponse(
        status_code=400,
        content=ErrorResponse(detail=str(exc)).dict()
    )

@app.get("/test")
async def test():
    raise ValueError("Invalid input")
AEmpty response with status 204
BPlain text 'Invalid input' with status 500
C{"detail": "Invalid input"} with status 400
DJSON with key 'error' and message 'Invalid input' with status 400
Step-by-Step Solution
Solution:
  1. Step 1: Understand exception handler behavior

    The handler catches ValueError and returns JSONResponse with ErrorResponse model content and status 400.
  2. Step 2: Check response content and status

    The content is the dict form of ErrorResponse with detail set to the exception message, so JSON has key 'detail' with 'Invalid input'.
  3. Final Answer:

    {"detail": "Invalid input"} with status 400 -> Option C
  4. Quick Check:

    Exception handler returns JSON with detail key [OK]
Quick Trick: Exception handler returns model dict as JSON with status [OK]
Common Mistakes:
MISTAKES
  • Expecting plain text instead of JSON
  • Confusing status codes
  • Assuming different JSON key names

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes