Bird
0
0

Identify the error in this middleware code snippet: ```python @app.middleware('http') async def error_middleware(request: Request, call_next): try: response = call_next(request) return response except Exception as e: return JSONResponse({'detail': str(e)}, status_code=500) ```

medium📝 Debug Q6 of 15
FastAPI - Error Handling
Identify the error in this middleware code snippet: ```python @app.middleware('http') async def error_middleware(request: Request, call_next): try: response = call_next(request) return response except Exception as e: return JSONResponse({'detail': str(e)}, status_code=500) ```
AMissing await before call_next(request)
BJSONResponse missing import
CException should not be caught globally
DMiddleware should not return responses
Step-by-Step Solution
Solution:
  1. Step 1: Check async call to call_next

    call_next is async and must be awaited to get the response.
  2. Step 2: Identify missing await

    Code calls call_next without await, causing a coroutine object to be returned instead of response.
  3. Final Answer:

    Missing await before call_next(request) -> Option A
  4. Quick Check:

    Async call_next requires await [OK]
Quick Trick: Always await async call_next(request) in middleware [OK]
Common Mistakes:
MISTAKES
  • Forgetting await on async calls
  • Ignoring import errors
  • Misunderstanding middleware response role

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes