From 5308fec3543abd91541ab28624f7061888c9ff03 Mon Sep 17 00:00:00 2001 From: Can Sarigol <56863826+cansarigol3megawatt@users.noreply.github.com> Date: Mon, 2 Aug 2021 18:12:12 +0200 Subject: [PATCH] Fixed for handling exceptions of asgi app call. (#2211) @cansarigol3megawatt Thanks for looking into this and getting the quick turnaround on this. I will :cherries: pick this into the 21.6 branch and get it out a little later tonight. --- sanic/__version__.py | 2 +- sanic/asgi.py | 5 ++++- tests/test_asgi.py | 31 ++++++++++++++++++++++++++++++- 3 files changed, 35 insertions(+), 3 deletions(-) diff --git a/sanic/__version__.py b/sanic/__version__.py index 79344950..74a495e2 100644 --- a/sanic/__version__.py +++ b/sanic/__version__.py @@ -1 +1 @@ -__version__ = "21.6.1" +__version__ = "21.6.2" diff --git a/sanic/asgi.py b/sanic/asgi.py index 5765a5cd..330ced5a 100644 --- a/sanic/asgi.py +++ b/sanic/asgi.py @@ -207,4 +207,7 @@ class ASGIApp: """ 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) diff --git a/tests/test_asgi.py b/tests/test_asgi.py index 5be3fd26..c707c12a 100644 --- a/tests/test_asgi.py +++ b/tests/test_asgi.py @@ -7,7 +7,7 @@ import uvicorn 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 @@ -346,3 +346,32 @@ async def test_content_type(app): _, 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 \ No newline at end of file