Skip to content

Exceptions raised from the middleware will be captured but the response will not be returned correctly #11857

Discussion options

You must be logged in to vote

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):

You should only raise HTTPException inside routing or endpoints. Middleware classes should instead just return appropriate responses directly.

Instead of raising HTTPException in your middleware, you can return response:

@app.middleware("http")
async def rate_limit_middleware(request: Request, call_next):
    return JSONResponse(
        status_code=status.HTTP_429_TOO_MANY_REQUESTS,
        content={"detail": "Rate limit exceed…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by superMaaax
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