-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Middleware Runs Twice if Route Not Found + Middleware Exception #2950
Comments
This seems to be where the router raises an exception and then https://github.com/sanic-org/sanic/blob/main/sanic/app.py#L1434-L1438 Then the middleware runs in the exception handler, it raises and that bubbles up to.. https://github.com/sanic-org/sanic/blob/main/sanic/http/http1.py#L149 which then calls the error response code which runs middleware if stage is |
Possible related to #2600 |
Note that I was able to work around this by preventing all middleware from raising via.. def register_middleware(app, middleware, *args, **kwargs):
async def wrapper(request, *mw_args, **mw_kwargs):
try:
return await middleware(request, *mw_args, **mw_kwargs)
except Exception as e:
response = app.error_handler.response(request, e)
if iscoroutine(response):
return await response
return response
app.register_middleware(wrapper, *args, **kwargs) But that feels more like a hack than a solution |
Maybe the code for running middleware should be similar to https://github.com/sanic-org/sanic/blob/main/sanic/app.py#L1223 |
I am not experiencing this:
|
How are you constructing This only seems to exhibit when a route is not found. Using the test client I seem to be able to exhibit the issue with: from sanic import Sanic
from sanic.exceptions import SanicException
from sanic.response import html
app = Sanic(__name__)
@app.middleware("request")
def my_middleware1(request):
print("Middleware 1 ran", flush=True)
@app.middleware("request")
def my_middleware2(request):
print("Middleware 2 ran", flush=True)
raise SanicException()
@app.get("/")
def index(request):
return html("<p>hello world</p>")
if __name__ == "__main__":
app.test_client.get("not-found")
|
It was with the REPL client.
Missed the part you were on a |
Is there an existing issue for this?
Describe the bug
Middleware will be run twice if the router raises an exception and then the middleware raises an Exception.
Output:
Code snippet
or
Expected Behavior
Request Middleware only runs once
How do you run Sanic?
Sanic CLI
Operating System
Linux
Sanic Version
23.12.1
Additional context
No response
The text was updated successfully, but these errors were encountered: