Bird
0
0

Find the bug in this FastAPI error handling code: ```python from fastapi import FastAPI, HTTPException app = FastAPI() @app.get("/products/{product_id}") async def get_product(product_id: int): try: if product_id == 0: raise HTTPException(status_code=404, detail="Product not found") except Exception as e: return {"error": str(e)} ```

medium📝 Debug Q7 of 15
FastAPI - Error Handling
Find the bug in this FastAPI error handling code: ```python from fastapi import FastAPI, HTTPException app = FastAPI() @app.get("/products/{product_id}") async def get_product(product_id: int): try: if product_id == 0: raise HTTPException(status_code=404, detail="Product not found") except Exception as e: return {"error": str(e)} ```
ARaising HTTPException inside try block causes syntax error.
BThe route path should use a query parameter instead.
CThe endpoint should return None when catching exceptions.
DCatching general Exception hides HTTPException status code and returns 200 OK.
Step-by-Step Solution
Solution:
  1. Step 1: Review exception catching

    Catching all exceptions including HTTPException and returning dict loses HTTP status code.
  2. Step 2: Understand HTTP response impact

    Returning dict causes FastAPI to send 200 OK with error message, not 404 error.
  3. Final Answer:

    Catching general Exception hides HTTPException status code and returns 200 OK. -> Option D
  4. Quick Check:

    Catch Exception then return dict = lose HTTP status [OK]
Quick Trick: Catch specific exceptions or re-raise HTTPException [OK]
Common Mistakes:
MISTAKES
  • Thinking raising HTTPException causes syntax error
  • Assuming returning None is correct
  • Confusing route path with query parameters

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes