Skip to content
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

Catch request middleware exceptions #2971

Merged
merged 3 commits into from
Jun 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions sanic/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -1209,10 +1209,15 @@ async def handle_exception(
# Request Middleware
# -------------------------------------------- #
if run_middleware:
middleware = (
request.route and request.route.extra.request_middleware
) or self.request_middleware
response = await self._run_request_middleware(request, middleware)
try:
middleware = (
request.route and request.route.extra.request_middleware
) or self.request_middleware
response = await self._run_request_middleware(
request, middleware
)
except Exception as e:
return await self.handle_exception(request, e, False)
# No middleware results
if not response:
try:
Expand Down
20 changes: 20 additions & 0 deletions tests/test_exceptions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import logging

from itertools import count

import pytest

from bs4 import BeautifulSoup
Expand Down Expand Up @@ -413,3 +415,21 @@ class CustomError(SanicException):
assert CustomError().message == CustomError.message == str(CustomError())
assert SanicException().message != ""
assert SanicException("").message == ""


def test_request_middleware_exception_on_404(app: Sanic):
"""See https://github.com/sanic-org/sanic/issues/2950"""
counter = count()

@app.on_request
def request_middleware(request):
value = next(counter)
raise Exception

@app.route("/")
async def handler(request): ...

_, response = app.test_client.get("/not-found")

assert response.status == 500
assert next(counter) == 1
Loading