1
from __future__ import annotations
5
from starlette._utils import is_async_callable
6
from starlette.concurrency import run_in_threadpool
7
from starlette.exceptions import HTTPException
8
from starlette.requests import Request
9
from starlette.types import ASGIApp, ExceptionHandler, Message, Receive, Scope, Send
10
from starlette.websockets import WebSocket
12
ExceptionHandlers = dict[Any, ExceptionHandler]
13
StatusHandlers = dict[int, ExceptionHandler]
16
def _lookup_exception_handler(exc_handlers: ExceptionHandlers, exc: Exception) -> ExceptionHandler | None:
17
for cls in type(exc).__mro__:
18
if cls in exc_handlers:
19
return exc_handlers[cls]
23
def wrap_app_handling_exceptions(app: ASGIApp, conn: Request | WebSocket) -> ASGIApp:
24
exception_handlers: ExceptionHandlers
25
status_handlers: StatusHandlers
27
exception_handlers, status_handlers = conn.scope["starlette.exception_handlers"]
29
exception_handlers, status_handlers = {}, {}
31
async def wrapped_app(scope: Scope, receive: Receive, send: Send) -> None:
32
response_started = False
34
async def sender(message: Message) -> None:
35
nonlocal response_started
37
if message["type"] == "http.response.start":
38
response_started = True
39
3
94
await send(message)
42
275
await app(scope, receive, sender)
43
except Exception as exc:
46
if isinstance(exc, HTTPException):
47
handler = status_handlers.get(exc.status_code)
50
handler = _lookup_exception_handler(exception_handlers, exc)
56
raise RuntimeError("Caught handled exception, but response already started.") from exc
58
if is_async_callable(handler):
59
response = await handler(conn, exc) # type: ignore[arg-type]
61
response = await run_in_threadpool(handler, conn, exc) # type: ignore[arg-type]
62
if response is not None:
63
await response(scope, receive, sender)