Bird
0
0

Identify the error in this FastAPI code snippet: ```python from fastapi import FastAPI, HTTPException app = FastAPI() @app.get("/users/{user_id}") async def get_user(user_id: int): try: if user_id < 0: raise HTTPException(status_code=400, detail="Negative ID") except HTTPException: return {"error": "Invalid user ID"} ```

medium📝 Debug Q6 of 15
FastAPI - Error Handling
Identify the error in this FastAPI code snippet: ```python from fastapi import FastAPI, HTTPException app = FastAPI() @app.get("/users/{user_id}") async def get_user(user_id: int): try: if user_id < 0: raise HTTPException(status_code=400, detail="Negative ID") except HTTPException: return {"error": "Invalid user ID"} ```
ARaising HTTPException inside try block is invalid syntax.
BCatching HTTPException and returning dict bypasses proper HTTP error response.
CThe endpoint should not use async def.
DThe route path is missing a trailing slash.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze exception handling logic

    The code catches HTTPException and returns a plain dict instead of raising it.
  2. Step 2: Understand FastAPI error response mechanism

    Returning a dict bypasses FastAPI's automatic HTTP error response formatting, losing status code 400.
  3. Final Answer:

    Catching HTTPException and returning dict bypasses proper HTTP error response. -> Option B
  4. Quick Check:

    Catch then return dict = no proper HTTP error [OK]
Quick Trick: Raise HTTPException, don't catch and return dict [OK]
Common Mistakes:
MISTAKES
  • Thinking raising HTTPException inside try is invalid
  • Believing async def is wrong here
  • Confusing route path syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes