Skip to content

Commit

Permalink
Prevent anyio.ExceptionGroup in error views under a BaseHTTPMiddleware (
Browse files Browse the repository at this point in the history
#1262)

* Prevent ExceptionGroup in error views under a BaseHTTPMiddleware

* Apply suggestion from @uSpike

Co-authored-by: euri10 <benoit.barthelet@gmail.com>
  • Loading branch information
florimondmanca and euri10 authored Oct 28, 2021
1 parent d87c93e commit 6c9bc55
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
10 changes: 9 additions & 1 deletion starlette/middleware/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,25 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
return

async def call_next(request: Request) -> Response:
app_exc: typing.Optional[Exception] = None
send_stream, recv_stream = anyio.create_memory_object_stream()

async def coro() -> None:
nonlocal app_exc

async with send_stream:
await self.app(scope, request.receive, send_stream.send)
try:
await self.app(scope, request.receive, send_stream.send)
except Exception as exc:
app_exc = exc

task_group.start_soon(coro)

try:
message = await recv_stream.receive()
except anyio.EndOfStream:
if app_exc is not None:
raise app_exc
raise RuntimeError("No response returned.")

assert message["type"] == "http.response.start"
Expand Down
5 changes: 3 additions & 2 deletions tests/middleware/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def homepage(request):

@app.route("/exc")
def exc(request):
raise Exception()
raise Exception("Exc")


@app.route("/no-response")
Expand All @@ -52,8 +52,9 @@ def test_custom_middleware(test_client_factory):
response = client.get("/")
assert response.headers["Custom-Header"] == "Example"

with pytest.raises(Exception):
with pytest.raises(Exception) as ctx:
response = client.get("/exc")
assert str(ctx.value) == "Exc"

with pytest.raises(RuntimeError):
response = client.get("/no-response")
Expand Down

0 comments on commit 6c9bc55

Please sign in to comment.