Bird
0
0

This middleware code causes an error:

medium📝 Debug Q7 of 15
FastAPI - Middleware and Hooks
This middleware code causes an error:
class ErrorMiddleware(BaseHTTPMiddleware):
    def dispatch(self, request, call_next):
        print("Start")
        response = await call_next(request)
        print("End")
        return response

app.add_middleware(ErrorMiddleware)

What is the error?
Aprint statements are not allowed in middleware.
Bdispatch method must be async to use await inside.
CMiddleware must be added before route definitions.
Ddispatch method should not have parameters.
Step-by-Step Solution
Solution:
  1. Step 1: Check method signature for async usage

    dispatch uses await, so it must be declared async.
  2. Step 2: Identify missing async keyword

    dispatch is missing async, causing syntax error on await.
  3. Final Answer:

    dispatch method must be async to use await inside. -> Option B
  4. Quick Check:

    await requires async function [OK]
Quick Trick: Use async def for dispatch when awaiting call_next [OK]
Common Mistakes:
MISTAKES
  • Forgetting async keyword on dispatch
  • Misunderstanding middleware method parameters
  • Thinking print causes errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes