Bird
0
0

Given this middleware code, what will be the response if a KeyError is raised inside the app?

medium📝 component behavior Q4 of 15
FastAPI - Error Handling
Given this middleware code, what will be the response if a KeyError is raised inside the app? ```python @app.middleware('http') async def catch_exceptions(request: Request, call_next): try: response = await call_next(request) return response except KeyError: return JSONResponse(status_code=400, content={'error': 'Key not found'}) ```
AHTTP 500 Internal Server Error
BHTTP 400 with JSON {'error': 'Key not found'}
CHTTP 404 Not Found
DNo response, server crashes
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the middleware exception handling

    The middleware catches KeyError exceptions and returns a JSONResponse with status 400 and error message.
  2. Step 2: Understand the effect on response

    When KeyError occurs, the middleware returns the custom JSON response instead of crashing.
  3. Final Answer:

    HTTP 400 with JSON {'error': 'Key not found'} -> Option B
  4. Quick Check:

    KeyError caught returns 400 JSON response [OK]
Quick Trick: Middleware catches KeyError and returns 400 JSON [OK]
Common Mistakes:
MISTAKES
  • Assuming server crashes
  • Expecting 500 error
  • Confusing 404 with 400

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes