Skip to content

Commit

Permalink
Prevent ExceptionGroup in error views under a BaseHTTPMiddleware
Browse files Browse the repository at this point in the history
  • Loading branch information
florimondmanca committed Aug 11, 2021
1 parent e45c579 commit 525215a
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
5 changes: 5 additions & 0 deletions starlette/middleware/base.py
@@ -1,3 +1,4 @@
import itertools
import typing

import anyio
Expand Down Expand Up @@ -34,6 +35,10 @@ async def coro() -> None:
try:
message = await recv_stream.receive()
except anyio.EndOfStream:
# HACK: give anyio a chance to surface any app exception first,
# in order to avoid an `anyio.ExceptionGroup`.
# See #1255.
await anyio.lowlevel.checkpoint()
raise RuntimeError("No response returned.")

assert message["type"] == "http.response.start"
Expand Down
5 changes: 3 additions & 2 deletions tests/middleware/test_base.py
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 525215a

Please sign in to comment.