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