Middlewares in subapps fail to return the correct status code #13992
-
First Check
Commit to Help
Example Codefrom fastapi import FastAPI, HTTPException, APIRouter, Request
from typing import Callable
sub_app = FastAPI()
router = APIRouter()
@sub_app.middleware("http")
async def do_something(request: Request, call_next: Callable):
raise HTTPException(status_code=401)
@router.get("/sub_path")
async def sub_path() -> None:
print('the code ran!')
sub_app.include_router(router, prefix="/sub_router")
app = FastAPI()
app.mount("/sub_app", sub_app) DescriptionI'm trying to use a middleware in a subapp that returns a http error using the HTTPException exception. Instead of it returning a 401, I'm getting a 500 with the exception message Operating SystemLinux, macOS Operating System DetailsNo response FastAPI Version0.116.1 Pydantic Version2.11.7 Python VersionPython 3.12.3 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
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.
|
Beta Was this translation helpful? Give feedback.
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: