0
0
FastAPIframework~20 mins

Global exception middleware in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Global Exception Middleware Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output when a ValueError is raised inside a FastAPI route with global exception middleware?

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')?

FastAPI
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")
A{"error": "Invalid input"} with status code 400
B500 Internal Server Error with default HTML response
C{"detail": "Invalid input"} with status code 422
DEmpty response with status code 204
Attempts:
2 left
💡 Hint

Think about what the middleware does when it catches a ValueError.

📝 Syntax
intermediate
2:00remaining
Which middleware code snippet correctly catches all exceptions and returns a JSON error response?

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.

A
async def middleware(request: Request, call_next):
    try:
        return await call_next(request)
    except Exception as e:
        return JSONResponse(status_code=500, content={"error": "Server error"})
B
async def middleware(request: Request, call_next):
    try:
        response = call_next(request)
        return response
    except Exception:
        return JSONResponse(status_code=500, content={"error": "Server error"})
C
async def middleware(request: Request, call_next):
    try:
        response = await call_next(request)
    except Exception as e:
        return JSONResponse(status_code=500, content={"error": str(e)})
    return response
D
async def middleware(request: Request, call_next):
    response = await call_next(request)
    except Exception:
        return JSONResponse(status_code=500, content={"error": "Server error"})
    return response
Attempts:
2 left
💡 Hint

Remember to await the call_next and handle exceptions properly.

🔧 Debug
advanced
3:00remaining
Why does this global exception middleware not catch exceptions raised in background tasks?

Given this middleware that catches exceptions during request processing, why are exceptions raised inside background tasks not caught by it?

FastAPI
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"}
AMiddleware must be registered with background task manager to catch those exceptions
BBackground tasks exceptions are caught but ignored silently by FastAPI
CBackground tasks run synchronously blocking middleware exception handling
DMiddleware only catches exceptions during request processing, background tasks run after response is sent
Attempts:
2 left
💡 Hint

Think about when background tasks run compared to the request lifecycle.

🧠 Conceptual
advanced
2:00remaining
What is the main benefit of using global exception middleware in FastAPI?

Why would a developer add a global exception middleware instead of handling exceptions inside each route?

ATo automatically retry failed requests without user code
BTo centralize error handling and provide consistent error responses across all routes
CTo log all requests regardless of errors
DTo improve performance by skipping exception handling in routes
Attempts:
2 left
💡 Hint

Think about code reuse and consistency in user experience.

state_output
expert
3:00remaining
What is the response status code and body when a KeyError is raised but middleware only catches ValueError?

Given a FastAPI app with middleware that catches only ValueError exceptions and returns status 400, what happens if a route raises KeyError('missing')?

FastAPI
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")
A{"error": "missing"} with status code 400
B422 Unprocessable Entity with JSON error detail
C500 Internal Server Error with default HTML error page
D200 OK with empty body
Attempts:
2 left
💡 Hint

Consider which exceptions the middleware catches and what happens to others.