0
0
FastAPIframework~10 mins

Global exception middleware in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the correct FastAPI class.

FastAPI
from fastapi import [1]
app = FastAPI()
Drag options to blanks, or click blank then click option'
ADepends
BRequest
CResponse
DFastAPI
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Request or Response instead of FastAPI.
Using lowercase fastapi instead of FastAPI.
2fill in blank
medium

Complete the code to import the ExceptionMiddleware from Starlette.

FastAPI
from starlette.middleware.errors import [1]
Drag options to blanks, or click blank then click option'
AExceptionMiddleware
BBaseHTTPMiddleware
CMiddleware
DErrorMiddleware
Attempts:
3 left
💡 Hint
Common Mistakes
Confusing ExceptionMiddleware with BaseHTTPMiddleware.
Using Middleware or ErrorMiddleware which do not exist in this context.
3fill in blank
hard

Fix the error in the middleware setup by completing the missing argument.

FastAPI
app.add_middleware(ExceptionMiddleware, app=[1], debug=False)
Drag options to blanks, or click blank then click option'
Arequest
Bself
Capp
Dmiddleware
Attempts:
3 left
💡 Hint
Common Mistakes
Passing 'request' or 'self' which are not the app instance.
Omitting the app argument entirely.
4fill in blank
hard

Fill both blanks to define a global exception handler function that returns JSON response.

FastAPI
from fastapi.responses import JSONResponse

@app.exception_handler([1])
async def global_exception_handler(request, exc):
    return JSONResponse(status_code=500, content={"detail": [2])
Drag options to blanks, or click blank then click option'
AException
B"An error occurred"
Cexc.detail
D"Internal Server Error"
Attempts:
3 left
💡 Hint
Common Mistakes
Using a specific exception class instead of Exception.
Returning exc.detail which may not exist.
5fill in blank
hard

Fill all three blanks to create a middleware that logs exceptions and re-raises them.

FastAPI
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]
Drag options to blanks, or click blank then click option'
AException
Bexc
DRuntimeError
Attempts:
3 left
💡 Hint
Common Mistakes
Catching RuntimeError instead of all Exceptions.
Printing wrong variable or re-raising a different exception.