Skip to content

Commit

Permalink
Fixed for handling exceptions of asgi app call. (#2211)
Browse files Browse the repository at this point in the history
@cansarigol3megawatt Thanks for looking into this and getting the quick turnaround on this. I will 🍒 pick this into the 21.6 branch and get it out a little later tonight.
  • Loading branch information
Can Sarigol authored and ahopkins committed Aug 2, 2021
1 parent 5a48b94 commit 5308fec
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
2 changes: 1 addition & 1 deletion sanic/__version__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "21.6.1"
__version__ = "21.6.2"
5 changes: 4 additions & 1 deletion sanic/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,4 +207,7 @@ async def __call__(self) -> None:
"""
Handle the incoming request.
"""
await self.sanic_app.handle_request(self.request)
try:
await self.sanic_app.handle_request(self.request)
except Exception as e:
await self.sanic_app.handle_exception(self.request, e)
31 changes: 30 additions & 1 deletion tests/test_asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from sanic import Sanic
from sanic.asgi import MockTransport
from sanic.exceptions import InvalidUsage
from sanic.exceptions import Forbidden, InvalidUsage, ServiceUnavailable
from sanic.request import Request
from sanic.response import json, text
from sanic.websocket import WebSocketConnection
Expand Down Expand Up @@ -346,3 +346,32 @@ def send_custom(request):

_, response = await app.asgi_client.get("/custom")
assert response.headers.get("content-type") == "somethingelse"


@pytest.mark.asyncio
async def test_request_handle_exception(app):
@app.get("/error-prone")
def _request(request):
raise ServiceUnavailable(message="Service unavailable")

_, response = await app.asgi_client.get("/wrong-path")
assert response.status_code == 404

_, response = await app.asgi_client.get("/error-prone")
assert response.status_code == 503

@pytest.mark.asyncio
async def test_request_exception_suppressed_by_middleware(app):
@app.get("/error-prone")
def _request(request):
raise ServiceUnavailable(message="Service unavailable")

@app.on_request
def forbidden(request):
raise Forbidden(message="forbidden")

_, response = await app.asgi_client.get("/wrong-path")
assert response.status_code == 403

_, response = await app.asgi_client.get("/error-prone")
assert response.status_code == 403

0 comments on commit 5308fec

Please sign in to comment.