Bird
0
0

Identify the error in this FastAPI code snippet for error handling:

medium📝 Debug Q14 of 15
FastAPI - Error Handling
Identify the error in this FastAPI code snippet for error handling:
from fastapi import FastAPI, HTTPException
app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    if item_id < 0:
        return HTTPException(status_code=400, detail="Invalid ID")
    return {"item_id": item_id}
AFunction should not be async
BMissing import for HTTPException
CShould use raise instead of return for HTTPException
DPath parameter should be a string, not int
Step-by-Step Solution
Solution:
  1. Step 1: Check how HTTPException is used

    HTTPException must be raised, not returned, to send an error response.
  2. Step 2: Identify the mistake in code

    The code returns HTTPException instead of raising it, so error handling won't work properly.
  3. Final Answer:

    Should use raise instead of return for HTTPException -> Option C
  4. Quick Check:

    Raise HTTPException, don't return it [OK]
Quick Trick: Use raise, not return, for HTTPException [OK]
Common Mistakes:
MISTAKES
  • Returning HTTPException instead of raising
  • Forgetting to import HTTPException
  • Wrong parameter types for path

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes