C. Should use raise instead of return for HTTPException
D. Path parameter should be a string, not int
Solution
Step 1: Check how HTTPException is used
HTTPException must be raised, not returned, to send an error response.
Step 2: Identify the mistake in code
The code returns HTTPException instead of raising it, so error handling won't work properly.
Final Answer:
Should use raise instead of return for HTTPException -> Option C
Quick Check:
Raise HTTPException, don't return it [OK]
Hint: Use raise, not return, for HTTPException [OK]
Common Mistakes:
Returning HTTPException instead of raising
Forgetting to import HTTPException
Wrong parameter types for path
5. You want to ensure your FastAPI app returns a 404 error with a custom message when an item is not found in the database. Which approach best ensures reliability and user clarity?
hard
A. Return {"error": "Item not found"} with status code 200.
B. Raise HTTPException(status_code=404, detail="Item not found") inside the endpoint when the item is missing.
C. Print an error message to the console and return an empty response.
D. Ignore missing items and return an empty dictionary.
Solution
Step 1: Understand proper error signaling
Raising HTTPException with 404 status clearly signals the error to clients.
Step 2: Compare alternatives for reliability
Returning 200 with error message or ignoring errors confuses clients and reduces reliability.
Final Answer:
Raise HTTPException(status_code=404, detail="Item not found") inside the endpoint when the item is missing. -> Option B
Quick Check:
Raise HTTPException for clear, reliable error responses [OK]
Hint: Raise HTTPException with 404 for missing items [OK]
Common Mistakes:
Returning error info with 200 status
Ignoring errors instead of signaling
Only logging errors without response
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.