Consider a FastAPI app with a global exception middleware that catches ValueError and returns a JSON response with status 400 and a message. What will the client receive if a route raises ValueError('Invalid input')?
from fastapi import FastAPI, Request from fastapi.responses import JSONResponse app = FastAPI() @app.middleware("http") async def catch_value_error(request: Request, call_next): try: response = await call_next(request) return response except ValueError as e: return JSONResponse(status_code=400, content={"error": str(e)}) @app.get("/test") async def test_route(): raise ValueError("Invalid input")
Think about what the middleware does when it catches a ValueError.
The middleware catches the ValueError and returns a JSON response with status 400 and the error message. So the client receives the JSON with the error message and status 400.
Choose the correct FastAPI middleware code that catches any exception during request processing and returns a JSON response with status 500 and a generic error message.
Remember to await the call_next and handle exceptions properly.
Option A correctly awaits call_next and catches exceptions. Option A misses await. Option A returns response outside try block which can cause errors. Option A has syntax error with misplaced except.
Given this middleware that catches exceptions during request processing, why are exceptions raised inside background tasks not caught by it?
from fastapi import FastAPI, BackgroundTasks, Request from fastapi.responses import JSONResponse app = FastAPI() @app.middleware("http") async def catch_exceptions(request: Request, call_next): try: response = await call_next(request) return response except Exception as e: return JSONResponse(status_code=500, content={"error": str(e)}) @app.get("/bg") async def bg_route(background_tasks: BackgroundTasks): def task(): raise RuntimeError("Background error") background_tasks.add_task(task) return {"message": "Task started"}
Think about when background tasks run compared to the request lifecycle.
Background tasks run after the response is sent, outside the middleware's request processing. So exceptions in background tasks are not caught by middleware.
Why would a developer add a global exception middleware instead of handling exceptions inside each route?
Think about code reuse and consistency in user experience.
Global exception middleware centralizes error handling so developers don't repeat code in every route and users get consistent error messages.
Given a FastAPI app with middleware that catches only ValueError exceptions and returns status 400, what happens if a route raises KeyError('missing')?
from fastapi import FastAPI, Request from fastapi.responses import JSONResponse app = FastAPI() @app.middleware("http") async def catch_value_error(request: Request, call_next): try: response = await call_next(request) return response except ValueError as e: return JSONResponse(status_code=400, content={"error": str(e)}) @app.get("/keyerror") async def key_error_route(): raise KeyError("missing")
Consider which exceptions the middleware catches and what happens to others.
The middleware only catches ValueError. A KeyError is not caught, so FastAPI returns its default 500 error response.