Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generic ExceptionHandler type #2403

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 5 additions & 5 deletions starlette/_exception_handler.py
Expand Up @@ -18,13 +18,13 @@
)
from starlette.websockets import WebSocket

ExceptionHandlers = typing.Dict[typing.Any, ExceptionHandler]
StatusHandlers = typing.Dict[int, ExceptionHandler]
ExceptionHandlers = typing.Dict[typing.Any, ExceptionHandler[Exception]]
StatusHandlers = typing.Dict[int, ExceptionHandler[Exception]]


def _lookup_exception_handler(
exc_handlers: ExceptionHandlers, exc: Exception
) -> ExceptionHandler | None:
) -> ExceptionHandler[Exception] | None:
for cls in type(exc).__mro__:
if cls in exc_handlers:
return exc_handlers[cls]
Expand Down Expand Up @@ -69,15 +69,15 @@ async def sender(message: Message) -> None:

if scope["type"] == "http":
nonlocal conn
handler = typing.cast(HTTPExceptionHandler, handler)
handler = typing.cast(HTTPExceptionHandler[Exception], handler)
conn = typing.cast(Request, conn)
if is_async_callable(handler):
response = await handler(conn, exc)
else:
response = await run_in_threadpool(handler, conn, exc)
await response(scope, receive, sender)
elif scope["type"] == "websocket":
handler = typing.cast(WebSocketExceptionHandler, handler)
handler = typing.cast(WebSocketExceptionHandler[Exception], handler)
conn = typing.cast(WebSocket, conn)
if is_async_callable(handler):
await handler(conn, exc)
Expand Down
17 changes: 13 additions & 4 deletions starlette/applications.py
Expand Up @@ -17,7 +17,15 @@
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import BaseRoute, Router
from starlette.types import ASGIApp, ExceptionHandler, Lifespan, Receive, Scope, Send
from starlette.types import (
ASGIApp,
ExceptionHandler,
ExceptionType,
Lifespan,
Receive,
Scope,
Send,
)
from starlette.websockets import WebSocket

AppType = typing.TypeVar("AppType", bound="Starlette")
Expand Down Expand Up @@ -59,7 +67,8 @@ def __init__(
debug: bool = False,
routes: typing.Sequence[BaseRoute] | None = None,
middleware: typing.Sequence[Middleware] | None = None,
exception_handlers: typing.Mapping[typing.Any, ExceptionHandler] | None = None,
exception_handlers: typing.Mapping[typing.Any, ExceptionHandler[ExceptionType]]
| None = None,
on_startup: typing.Sequence[typing.Callable[[], typing.Any]] | None = None,
on_shutdown: typing.Sequence[typing.Callable[[], typing.Any]] | None = None,
lifespan: Lifespan[AppType] | None = None,
Expand Down Expand Up @@ -143,8 +152,8 @@ def add_middleware(

def add_exception_handler(
self,
exc_class_or_status_code: int | type[Exception],
handler: ExceptionHandler,
exc_class_or_status_code: int | type[ExceptionType],
handler: ExceptionHandler[ExceptionType],
) -> None: # pragma: no cover
self.exception_handlers[exc_class_or_status_code] = handler

Expand Down
10 changes: 7 additions & 3 deletions starlette/types.py
Expand Up @@ -21,10 +21,14 @@
]
Lifespan = typing.Union[StatelessLifespan[AppType], StatefulLifespan[AppType]]

ExceptionType = typing.TypeVar("ExceptionType", bound=Exception)

HTTPExceptionHandler = typing.Callable[
["Request", Exception], "Response | typing.Awaitable[Response]"
["Request", ExceptionType], "Response | typing.Awaitable[Response]"
]
WebSocketExceptionHandler = typing.Callable[
["WebSocket", Exception], typing.Awaitable[None]
["WebSocket", ExceptionType], typing.Awaitable[None]
]
ExceptionHandler = typing.Union[
HTTPExceptionHandler[ExceptionType], WebSocketExceptionHandler[ExceptionType]
]
ExceptionHandler = typing.Union[HTTPExceptionHandler, WebSocketExceptionHandler]