Fixed for handling exceptions of asgi app call. (#2211)

@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.
This commit is contained in:
Can Sarigol 2021-08-02 18:12:12 +02:00 committed by Adam Hopkins
parent 5a48b94089
commit 5308fec354
No known key found for this signature in database
GPG Key ID: 6A33C08203F67A28
3 changed files with 35 additions and 3 deletions

View File

@ -1 +1 @@
__version__ = "21.6.1" __version__ = "21.6.2"

View File

@ -207,4 +207,7 @@ class ASGIApp:
""" """
Handle the incoming request. 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)

View File

@ -7,7 +7,7 @@ import uvicorn
from sanic import Sanic from sanic import Sanic
from sanic.asgi import MockTransport from sanic.asgi import MockTransport
from sanic.exceptions import InvalidUsage from sanic.exceptions import Forbidden, InvalidUsage, ServiceUnavailable
from sanic.request import Request from sanic.request import Request
from sanic.response import json, text from sanic.response import json, text
from sanic.websocket import WebSocketConnection from sanic.websocket import WebSocketConnection
@ -346,3 +346,32 @@ async def test_content_type(app):
_, response = await app.asgi_client.get("/custom") _, response = await app.asgi_client.get("/custom")
assert response.headers.get("content-type") == "somethingelse" 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