Exceptions raised from the middleware will be captured but the response will not be returned correctly #11857
-
First Check
Commit to Help
Example Codefrom fastapi import FastAPI
app = FastAPI()
@app.middleware("http")
async def rate_limit_middleware(request: Request, call_next):
# Let's say it's rejecting the request no matter how, but in the end, the server will respond 500 Internal Server Error instead of 429
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Rate limit exceeded")
# return await middleware.rate_limit(request, call_next)DescriptionI'm writing a Rate Limiter as a middleware for the service I'm developing. The Exceptions raised from the API function work pretty well (raised, catched, and returned response correctly). However, I found that the HTTPException raised from the middleware will not be returned correctly. It will respond 500 Internal Server Error instead of 429. I really have to write Operating SystemmacOS Operating System DetailsNo response FastAPI Version0.111.0 Pydantic Version2.6.2 Python VersionPython 3.12.2 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
You can't handle exceptions from middleware using exception handlers. Using exception handler you can only handle HTTPExceptions that were raised from endpoints and router.
Instead of raising HTTPException in your middleware, you can return response: |
Beta Was this translation helpful? Give feedback.

You can't handle exceptions from middleware using exception handlers. Using exception handler you can only handle HTTPExceptions that were raised from endpoints and router.
You can read more in Starlette docs (https://www.starlette.io/exceptions/#httpexception):
Instead of raising HTTPException in your middleware, you can return response: