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 7 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 @@ -16,13 +16,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
) -> typing.Optional[ExceptionHandler]:
) -> typing.Optional[ExceptionHandler[Exception]]:
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 @@ -13,7 +13,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 @@ -55,7 +63,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: typing.Optional[Lifespan["AppType"]] = None,
Expand Down Expand Up @@ -139,8 +148,8 @@ def add_middleware(

def add_exception_handler(
self,
exc_class_or_status_code: int | typing.Type[Exception],
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NB: this has now been tightened so that the Exception for exc_class_or_status_code must match the Exception in the handler Callable.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Kludex isn't this a deprecated function?

Copy link
Sponsor Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No. We never deprecated add_exception_handler... 🤔

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BTW, to be more precise, the Exception in the handler Callable is still contravariant, so this passes as one would hope:

def fallback_exception_handler(request: Request, exc: Exception) -> JSONResponse:
    ...

app.add_exception_handler(Exception, fallback_exception_handler)
app.add_exception_handler(MyException, fallback_exception_handler)

ie: the ExceptionType TypeVar changes the handler Callable Exception to a type parameter. The value of this type parameter is provided at the call site, eg: in the example here its Exception in the first call, and MyException in the second. But the contravariance of Callable remains.

And also the Callable is still not covariant, so this fails as one might expect:

def my_exception_handler(request: Request, exc: MyException) -> JSONResponse:
    ...

# this fails, because subtypes of the exc_class_or_status_code Exception in the Callable 
# aren't permitted ie: Callable is not covariant in the function's input parameter types
app.add_exception_handler(Exception, my_exception_handler)

handler: ExceptionHandler,
exc_class_or_status_code: int | typing.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, contravariant=True)

HTTPExceptionHandler = typing.Callable[
["Request", Exception], typing.Union["Response", typing.Awaitable["Response"]]
["Request", ExceptionType], typing.Union["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]