Complete the code to import the correct FastAPI class.
from fastapi import [1] app = FastAPI()
The FastAPI class is imported from fastapi to create the app instance.
Complete the code to import the ExceptionMiddleware from Starlette.
from starlette.middleware.errors import [1]
ExceptionMiddleware is the middleware class used to catch global exceptions.
Fix the error in the middleware setup by completing the missing argument.
app.add_middleware(ExceptionMiddleware, app=[1], debug=False)
The ExceptionMiddleware requires the app instance passed as the 'app' argument.
Fill both blanks to define a global exception handler function that returns JSON response.
from fastapi.responses import JSONResponse @app.exception_handler([1]) async def global_exception_handler(request, exc): return JSONResponse(status_code=500, content={"detail": [2])
The handler catches all Exceptions and returns a JSON with a simple error message.
Fill all three blanks to create a middleware that logs exceptions and re-raises them.
from starlette.middleware.base import BaseHTTPMiddleware class LoggingExceptionMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): try: response = await call_next(request) return response except [1] as exc: print(f"Error: [2]") raise [3]
The middleware catches all exceptions, logs the exception object, and re-raises it.