Skip to content

Middlewares in subapps fail to return the correct status code #13992

Discussion options

You must be logged in to vote

Don’t raise HTTPException from middleware (especially inside a mounted sub-app). Exception handlers don’t catch exceptions raised in middleware, so Starlette logs “Caught handled exception, but response already started” and you get a 500.
The recommended pattern is to return a response from middleware. Something like that:

from fastapi import FastAPI, APIRouter, Request
from fastapi.responses import JSONResponse
from typing import Callable

sub_app = FastAPI()
router = APIRouter()

@sub_app.middleware("http")
async def do_something(request: Request, call_next: Callable):
    # ... your auth/checks here ...
    return JSONResponse(status_code=401, content={"detail": "Unauthorized"})
    # …

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by YuriiMotov
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Question or problem
2 participants